How to Group By with Order By Desc in Laravel?
This post is focused on laravel group by with order by desc. if you want to see example of laravel eloquent group by order by desc then you are a right place. you can understand a concept of laravel group by orderby. i would like to show you laravel eloquent group by and order by. it will also usable with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 app.
In this post, i will give you some solution for how to get records with order by desc with group by in laravel application. when you use laravel eloquent group by with order by desc then it's now working as we want. we need to get last added records first with group by.
Here, i will give you some solution with how you to order by before group by in laravel eloquent.
So let's see bellow solution:
Solution 1:
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$messages = Message::select("*")
->where('receiver_id',$id)
->orderBy('created_at', 'desc')
->get()
->unique('sender_id');
dd($messages);
}
Solution 2:
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$message = Message::orderBy('created_at','DESC');
$messages = DB::table(DB::raw("({$message->toSql()}) as sub"))
->where('receiver_id',$id)
->groupBy('sender_id')
->get();
dd($messages);
}
Solution 3:
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$messages = Message::select(DB::raw('*, max(created_at) as created_at'))
->where('receiver_id',$id)
->orderBy('created_at', 'desc')
->groupBy('sender_id')
->get();
dd($messages);
}
Solution 4:
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$messages = Message::select("*")
->where('receiver_id',$id)
->orderBy('created_at', 'desc')
->groupBy('sender_id')
->get();
dd($messages);
}
I hope it can help you...

Hardik Savani
I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel orWhere Condition using Eloquent Query
- Laravel Wherein Query Example
- How to Create and Use Query Scope in Laravel Eloquent
- How to use whereHas with orWhereHas in Laravel?
- How to use Union query with Laravel Eloquent?
- Laravel Has Many Through Eloquent Relationship Tutorial
- Laravel Where Clause with date_format() Example
- Group by year month example in Laravel using Query Builder
- How to group by multiple columns in Laravel Query Builder?
- Laravel Select with Count Query with Group by Example
- Laravel Like Query Example using Eloquent Where Clause
- GROUP_CONCAT with different SEPARATOR in Laravel Example