sahar_mkr's avatar

cast

hi everybode. I want to use group by according to the month of my created_at column, I've used cast property in my model like this: protected $casts = ["created_at" => "datetime:m"]; when I use dd() to check the output I don't see any changes in created_at attribute and it's still in carbon format, Is there anything wrong in my solution? thank you all

0 likes
5 replies
tisuchi's avatar

@sahar_mkr How about trying this?

$data = Appointment::selectRaw('MONTH(created_at) as month, YEAR(created_at) as year, count(*) as count')
->groupBy('month', 'year')
->get();
1 like
sahar_mkr's avatar

@tisuchi thanks for your reply, actually I just want to fetch data from database with eloquent, and then use groupBy Month of created_at, do you have any suggestion for that?

Dragon_Worrior's avatar

@sahar_mkr try this.

$months = NewsItem::groupBy(function($d) {
    return Carbon::parse($d->created_at)->format('m');
})->get();```
sahar_mkr's avatar

@Dragon_Worrior thanks, actually I want to write a function for the part you wrote, because I want to use this group by in several collections, or, use casting in order to find month, and then just use groupBy function, is it possible?

Dragon_Worrior's avatar

@sahar_mkr I hope you got your answer here.

https://www.itsolutionstuff.com/post/how-to-use-carbon-in-laravel-blade-or-controller-fileexample.html

Please or to participate in this conversation.