In this tutorial we will go over the demonstration of laravel eloquent group by and order by. you can understand a concept of order by desc with group by laravel. we will help you to give example of laravel group by with order by desc. you will learn laravel eloquent group by order by desc.
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...
Do you like below Tutorials ?
- PHP Laravel 5.5 - import export data into excel and csv using maatwebsite
- Laravel 7.x and 6.x create custom facade example from scratch
- Node JS - Get Real time online users counter using socket io example
- PHP Laravel 7.x and 6.x - Bootstrap Admin Theme Integration example from scratch
- MySQL Query - How to select records of today to next Sunday ?
- Laravel 7.x and 6.x - username custom validation example
- Laravel 5.5 - Import Extract zip file using chumper/zipper package
- PHP Laravel Set Custom Validation Error Messages Example