Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel implode pluck to array dates to string

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?

like image 249
eskimo Avatar asked May 20 '26 21:05

eskimo


1 Answers

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();
like image 140
Mohamad Nowruzi Avatar answered May 22 '26 10:05

Mohamad Nowruzi