1👍
✅
$value->created_at
is a full date/time string. Since you want to organize it by dates, then you’ll need to format it first. Thankfully, Laravel’s timestamps are automatically converted to Carbon, so it’s easy to format
$attrs[$value->created_at->toDateString()][] = $value->order;
If you want just the year/month, then use format()
instead
$attrs[$value->created_at->format('Y-m')][] = $value->order;
Edit I see now you’re using query builder (DB), not Eloquent, so you’ll need to actually parse the timestamp separately.
$date = Carbon::create($value->created_at);
$attrs[$date->toDateString()][] = $value->order; // 2021-07-14
$attrs[$date->format('Y-m')][] = $value->order; // 2021-07
0👍
If you are using collection then
$user=DB::table('analytics')->get()
->mapToDictionary(function ($analytics){
$date=Carbon::parse($analytics->created_at)->format('d-m-Y');
$data[$date]=$analytics->order;
return $data;
})->toArray();
0👍
My recommendation would be to use Eloquent instead of the DB query builder. If you have an Analytic
model, then this is quite simple. You could just add created_at
to your $dates
array and it will automatically be cast as a Carbon
instance. For instance, in your model:
protected $dates = ['created_at'];
Source:stackexchange.com