Reputation: 443
I am querying my users to return a list of them, here is an example
$user_list = DB::table('users')
->select('name','email','created_at')
->orderBy('created_at')
->get();
I am seeing the correct results, but I am trying to split these results up so that they are grouped by month.
Does anybody have some docs I can read or some example code of doing this?
Upvotes: 0
Views: 5147
Reputation: 4365
Try this:
$user_list = DB::table('users')
->select('name','email','created_at')
->orderBy('created_at')
->groupBy(DB::raw('MONTH(created_at)'))
->get();
Upvotes: 4
Reputation: 3397
$groupedUsers = $users->mapToGroups(function ($user, $key) {
return $user->created_at->month => $user;
});
This may be a little less code than some of the others. They will all work though. Here, you can replace $users
with User::all()
if you have your model set up correctly.
Upvotes: 0
Reputation: 936
There is section in the docs, where you can find an information about the groupBy
method - method
In your code you can write this():
$user_list = User::select('name','email','created_at')
->orderBy('created_at')->get();// get User collection
$user_list->groupBy(function ($item, $key) {
return $item->created_at->format('m');
});
Upvotes: 0