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

Create custom library or custom class in Laravel 8 / 9

December 21, 2021November 6, 2023

Laravel provides various packages and library to enhance our application features and functionalities but sometime we want our custom class in laravel to handle the few features of the application. Thus I this article i will show you to create a class and use it using the alias or directly…

Read More
Laravel Laravel 10 Image Upload with Preview Example

Laravel 10 Image Upload: A Comprehensive Tutorial

October 23, 2023March 16, 2024

Laravel 10, renowned for its efficiency and simplicity, offers a seamless solution for handling image uploads in web applications. In Laravel 10 Image Upload tutorial, we will guide you through the process of uploading and displaying images using the robust features of Laravel 10. Whether you are a beginner or…

Read More
Php How to Import or Convert ExcelCSV to HTML in laravel 8 9

How to Import or Convert Excel/CSV to HTML in laravel 8 / 9?

May 7, 2022May 13, 2022

Excel or CSV are used to store large set of data to analyses and for reporting. In this article we will learn to import excel or CSV in laravel. This tutorial is best fit to you if you want to understand the basic of import in database table with custom…

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

  • July 2025
  • 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

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version