Group by two or multiple columns in Laravel

November 7th, 2022

Laravel groupBy(): Collection method

group by 1 column:

accepts column name or function

1// group by user_id, which is column name on posts table
2$posts = Post::with('author')->get()->groupBy('user_id');
3 
4// group by also accepts function: group by author name (author is relationship on posts model)
5$posts = Post::with('author')->get()->groupBy(fn($post) => $post->author->name);

group by 2 columns:

accepts array of 2 column names or 2 functions:

1// group by author name and published year
2$posts = Post::with('author')->get()
3 ->groupBy([fn($post) => $post->author->name, fn($post) => $post->published_at->year]);
4 
5dd($posts)

Related Posts