Laravel Eloquent Query | Laravel Group By with Order By Desc

Raviya Technical
1 min readSep 12, 2021

--

This post is focused on the laravel group by with order by desc. if you want to see an example of a laravel eloquent group by order by desc then you are in the right place. you can understand the concept of the laravel group by orderby. I would like to show you the laravel eloquent group by and order by. it will also be usable with the laravel app.

In this post, I will give you some solutions for how to get records with an order by desc with the 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 the last added records first with the group by.

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);}

--

--