Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iamlux20's avatar

Predetermined ID number

Was wondering if Laravel can add a minor syntax to predetermine the latest ID number. To simplify this code:

$lastId = Model::select('id')->orderBy('id', 'desc')->first();
$predeterminedId = ++$lastId->id;

0 likes
4 replies
jlrdw's avatar

Mysql LAST_INSERT_ID();

   $lastInsertedID = $users->lastInsertId();

2 likes
rodrigo.pedra's avatar
Level 56

From your variable's name, it seems you want to know the next ID before performing any inserts on the database.

Actually your code can be simplified to:

$predeterminedId = Model::max('id') + 1;

But I wouldn't rely on that value for "reserving" a future ID.

Web apps can handle multiple concurrent requests, so unless you are using some lock mechanism, you can't be sure this will be the next generated ID from your database in case you want to use it before performing any inserts.

If you want the last generated ID from an insert that was already performed in the database, see @jlrdw 's answer.

1 like
iamlux20's avatar

Thanks @rodrigo.pedra and @jlrdw

Am using Hashids\Hashids to mask id number for the url of items, and needs to have an integer as input.

Although my app only has a single admin account, my next step is to have an auto-signout feature if account is logged in to another device/browser to prevent 2 admin accounts trying to use the predeterminedId and creating an error before creation.

1 like

Please or to participate in this conversation.