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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With