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

ahsan's avatar
Level 46

how to unique increment simultaneous requests

we have sales table and want to add unique sale number in table

here is the code but it's duplicate the numbers with simultaneous requests.

if 5 requests at same time it's not working perfectly because when we fetch last number from database it's give us sometime old number.

$sale->create([
    'number' => optional($sale->latest('id')->first())->number + 1,
    'amount' => 20,
]);

there are 2 queries same time first fetch old number then increment. but it's not good for simultaneous requests.

any solution here?

thanks

0 likes
6 replies
rin4ik's avatar

try this

'number' =>increment(optional($sale->latest('id')->first())->number)
Snapey's avatar

You need to lock the table whilst you create the new record

click's avatar

Aren't you just recreating the auto increment functionality here? You take the highest id you can find increment it with one and than try to store it in a separate field.

That is exactly what the auto increment method of mysql does, only smarter and without the possibility of duplicates. So conclusion. Isn't the 'id' field of the sale record not the number you are looking for?

ahsan's avatar
Level 46

@m-rk no i want to increment number column too

all working fine but not working with same time multiple requests.

2 likes
click's avatar

@ahsan but is your id value different than your number column in your database?

Please or to participate in this conversation.