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

AliPadida95's avatar

How to get the next autoincrement id

Hi, I am trying to get the next autoincrement id of a table in laravel. i.g. current value of auto-increment id is 4. So the next will 5, right? Can I somehow get the next autoincrment id?

0 likes
12 replies
calin.ionut's avatar

for me is not working in laravel 9

  $productsInfo = DB::select("SHOW TABLE STATUS LIKE 'products'");
        $nextID = $productsInfo[0]->Auto_increment;

the nextID is the last id (not the next)

any idea why? In older version worked....

2 likes
eugenefvdm's avatar

@calin.ionut Yes I agree doesn't seem to work with my current stack too. However this works for me:

$nextTransactionId = Transaction::orderBy('id','desc')->first()->id + 1;
3 likes
Sinnbeck's avatar

@eugenevdm I am mostly curious how getting the next ID is useful at all. Chances are that the ID is taken by another user, by the time the page is stored

The reason it is problematic is this. Lets say it returns 45. But what you don't know is that there was a 46 earlier that was deleted. So you tell the system that the next id will be 46, when in reality it will be 47

3 likes
Snapey's avatar

@eugenevdm

  1. if you have more than one user what you think is the next number can be taken immediately after you read it and before you use it. Two users end up with the same number

  2. if you use a transaction, and it fails and gets rolled back, there will be a gap in the numbers

  3. the issue that @sinnbeck mentioned

  4. Its a code smell. if you think you need to do this then something is wrong with your logic that can be fixed some other way

6 likes
Snapey's avatar

Don't do it. Its invalid as soon as you have fetched it.

There is absolutely no valid reason to get an autoincrement value ahead of writing a record.

2 likes
longway's avatar

@Snapey I actually have a case for this, I need to import data from another system with different ID, I need to know the new ID so I can have a mapping between the two system, and use the new ID to import all related data.

1 like
Snapey's avatar

@longway you don't need to know it beforehand? Write the main record, get its id and then write the related records

1 like
vicodeveloper's avatar

Hi everyone) I have an ideea. You can use uuid, but for this, you need to change primary id in your table. In your migration you need to change $table->id(); to $table->uuid('id')->primary(); In your model you need to add use HasUuids; (use Illuminate\Database\Eloquent\Concerns\HasUuids;)

And then, you can generate uuid before save data.

P.S. It is my first message on Laracast :)

Please or to participate in this conversation.