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

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

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