Laravel implode pluck to array dates to string

Viewed 357

If I have this query

$posts = Post::select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as count'))
                ->groupBy('date')
                ->get();

and then in blade do this to produce an ApexChart

var options = {
  chart: {
    type: 'bar',
    height: '300px',
  },
  series: [{
    name: 'Posts',
    data: [{{ implode(',', $posts->pluck('count')->toArray()) }}]
  }],
  xaxis: {
    type: 'datetime',
    labels: {
        show: true,
        format: 'yyyy-MM-dd',
    },
    categories: [{{ implode(',', $posts->pluck('date')->toArray()) }}]
  },
  fill: {
        colors: ['#0000FF']
    }
}

Which produces this for categories:

categories: [2020-11-21,2020-11-30,2020-12-02,2020-12-05,2020-12-08,2020-12-16,2020-12-24,2021-01-01,2021-01-02,2021-01-04,2021-01-07,2021-01-08,2021-01-09]

This renders the chart incorrectly, every date label is displayed as 'Jan 1'. I guess this is because the values are supposed to be strings like so:

categories: ['2020-11-21','2020-11-30',...]

Is this possible while preserving that beautiful one-liner?

2 Answers

Why not just convert the dates to JSON? this should produce valid JSON data. Instead of having to convert objects into the correct strings.

categories: {{ $posts->pluck('date')->toJson() }}

Add quotes to the date strings:

$posts->pluck('date')->map(function($item) {
    return "'$item'";
})->toArray();

You can also write the same thing shorter:

$posts->pluck('date')->map(fn($i) => "'$i'")->toArray();
Related