W3docs

Laravel Query Builder where max id

In Laravel, you can use the Query Builder's max method to retrieve the maximum value of a specific column.

Get max id

In Laravel, you can use the Query Builder's max method to retrieve the maximum value of a specific column. For example, to retrieve the highest ID from a table called users, you can use the following code:

$maxId = DB::table('users')->max('id');
Info

Watch a video course: Learn object oriented PHP

This returns an integer if the table contains rows, or null if the table is empty. For production readiness, handle the null case explicitly:

$maxId = DB::table('users')->max('id') ?? 0;

If you are using Eloquent, the equivalent is $maxId = User::max('id');.