Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Get Last Record With Group By in Laravel Eloquent

How to Get Last Record With Group By in Laravel Eloquent ?

Aman Jain, September 7, 2022March 16, 2024

In this tutorial we will learn to get last record with group by in laravel eloquent. while working with group by in mysql its gives first record from the group by records that means if you have multiple record with same id and you want the most recent record or last record with same id then mysql will only give you first record not last so to overcome this problem we come here to resolve it in laravel eloquent way.

This example will work in all version of laravel including laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9. we will use whereIn, join and DB::raw methods to get the records.

Suppose we have a group_messages table and here is follow structure and data

iduser_idgroup_idmessageis_readupdated_atcreated_at
111hi12022-09-07 22:00:002022-09-07 22:00:00
211hi sec02022-09-07 22:02:002022-09-07 22:02:00
321hi last12022-09-07 23:00:002022-09-07 23:00:00
422hi g202022-09-07 22:00:002022-09-07 22:00:00
532hi g2 sec12022-09-07 22:02:002022-09-07 22:02:00
632hi g2 last12022-09-07 23:00:002022-09-07 23:00:00
group_messages

so if we group by the group_id column using the eloquent as

GroupMessages::groupBy('group_id')->get();

then we will get the below result

iduser_idgroup_idmessageis_readupdated_atcreated_at
111hi12022-09-07 22:00:002022-09-07 22:00:00
422hi02022-09-07 22:00:002022-09-07 22:00:00
group_messages with group by

But in real case scenarios we want the last row record of group by rows so here is the solution 1

Solution 1 :

In this solution we will use two queries one to get max id and another to get the records of first eloquent by passing it into second query.

$groupMessages = GroupMessages::select(\DB::raw("max(group_messages.id)"))
                               ->groupBy('group_messages.group_id');

$allMesages    = GroupMessages::whereIn("id",$groupMessages)
                               ->orderBy("id","DESC")
                               ->paginate();                            

So here we only added \DB::raw("group_messages.id") and then used another query for where in .

Solution 2 :

In this solution we will use two queries as well one to get max id and in another we will use inner join with merge bindings.

$groupMessages = GroupMessage::select(\DB::raw("max(group_messages.id) as max_id"))
        ->groupBy('group_messages.group_id');

$allMesages    = GroupMessage::join(\DB::raw("({$groupMessages->toSql()}) as g2"), function ($join) {
                     $join->on("g2.max_id", "=", "group_messages.id");
               })->mergeBindings($groupMessages->getQuery())
                 ->orderBy("id", "DESC")
                 ->get();

So here we only added \DB::raw("group_messages.id") and then used join(\DB::raw("({$groupMessages->toSql()}) as g2"), .

Related

Php Laravel Laravel 9 Eloquentgroupbylaravellast

Post navigation

Previous post
Next post

Related Posts

Php Laravel session

How to set and get session in Laravel 8?

November 8, 2021November 17, 2021

Laravel has its own class to manage the session using the file system, redis, array, cookie and database. Session are used to keep the information about the user across the multiple request. As we know PHP is a server side language and all information lost after the response, so keep…

Read More
Php Laravel multiple orderBy clause with example

Laravel multiple orderBy clause with example

October 6, 2022March 16, 2024

In this blog post, we will take a look at how to use the Laravel multiple orderBy clause in the Eloquent ORM. You can order query results by multiple columns using the orderBy method. This is useful when you want to sort by multiple criteria. In this post, we’ll show…

Read More
Php How to Send Mail in Laravel Through Sendmail and SMTP

How to Send Mail in Laravel 8 / 9 Through Sendmail and SMTP ?

May 8, 2022August 20, 2022

Email is very common operation of any website like sending an email to users after registration, Send newsletters to users and many more. In this tutorial i will show you to send Mail in Laravel Through Sendmail and SMTP. Laravel provides multiple drivers or services to send mail from different…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version