ItSolutionStuff.com

Laravel Group By with Max Value Query Example

By Hardik Savani β€’ April 16, 2024
Laravel

Hey,

In this tute, we will discuss laravel group by with max value. step by step explain laravel group by max value. We will look at example of laravel group by max(id). let’s discuss about laravel collection group by max.

If you want to get records with group by query and you need to get maximum date, max id, max value or max number then how you will do it. generally group by get first record, but if you need max value records then i will show you some simple query example and you can fix your problem.

you can use this query in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.

let's see some example query:

Example 1: Laravel Group By with Max ID

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$data = UserPayment::select('id', 'user_id', DB::raw('MAX(id) as max_id'))

->where('is_paid', 1)

->groupBy('user_id')

->get();

dd($data);

}

Example 2: Laravel Group By with Max Date

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$data = UserPayment::select('id', 'user_id', DB::raw('MAX(paid_date) as max_paid_date'))

->where('is_paid', 1)

->groupBy('user_id')

->get();

dd($data);

}

Example 3: Laravel Group By with Max Value

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$data = UserPayment::select('id', 'user_id', DB::raw('MAX(amount) as max_amount'))

->where('is_paid', 1)

->groupBy('user_id')

->get();

dd($data);

}

i hope it can help you...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

Laravel Case Sensitive Query Search Example

Read Now β†’
β˜…

Laravel Eloquent Group By Year with Sum Example

Read Now β†’
β˜…

Laravel Group By Date and Sum Example

Read Now β†’
β˜…

Laravel Eloquent Group By with Month and Year Example

Read Now β†’
β˜…

Laravel Eloquent Left Join Where Null Condition Example

Read Now β†’
β˜…

Laravel Eloquent Group By Example

Read Now β†’
β˜…

Laravel Eloquent whereNotNull() Query Example

Read Now β†’
β˜…

How to Group By with Order By Desc in Laravel?

Read Now β†’
β˜…

Laravel One to Many Eloquent Relationship Tutorial

Read Now β†’
β˜…

Laravel Many to Many Eloquent Relationship Tutorial

Read Now β†’
β˜…

Laravel Has Many Through Eloquent Relationship Tutorial

Read Now β†’