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

Image for post
Image for post

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

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:

Written by

Web geek, Self-taught full-stack web developer, Learning Python, Laravel, Vuejs, UX/UI design, Nuclear Physicist PhD

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store