Laravel —How to get maximum minimum average value and sum of a column — query builder method

Panjeh
3 min readDec 7, 2018

--

Laravel query builder provides a variety of aggregate methods such as count, max, min, avg, and sum. You may call any of these methods after constructing your query.

$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');

Before you continue with the rest of this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

You may combine these methods with other clauses:

$price = DB::table('orders')
->where('finalized', 1)
->avg('price');

If you want to find the maximum id number of a table you have some options in Laravel:

DB::table('users')->max('id');
or
use App\User; // set at the top
User::max('id');

The alternative is:

$newestUser = User::orderBy('id', 'desc')->first();
$maxId = $newestUser->id;

if you have a created_at column with the date you could get in Laravel the maximum id value like this:

$maxId = User::latest()->value('id');

Thank you for reading! If you enjoyed this article:

Clap it ! Share it! Follow Me in Medium!

Also I’d like to hear your opinion on this article. If you have any doubt, question or suggestion please leave a comment below.

Have a very wonderful day!

Previous Stories You will Love:

--

--

Panjeh
Panjeh

Written by Panjeh

Posting about Python and Laravel

Responses (1)