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

vincent15000's avatar

lockForUpdate() doesn't work

Hello,

I'm trying to get lockForUpdate() working, but it doesn't.

I have also tried with transactions, but it doesn't work better.

The documentation seems to be contradictory.

https://laravel.com/docs/11.x/queries#pessimistic-locking

A shared lock prevents the selected rows from being modified until your transaction is committed.

While not obligatory, it is recommended to wrap pessimistic locks within a transaction.

Not sure to understand : are transactions necessary to work with pessimistic locks ?

Thanks for your help.

V

0 likes
2 replies
Tray2's avatar
Tray2
Best Answer
Level 73

A transaction is just valid for that particular session.

It waits for a commit or a rollback.

Transaction aren't really that effective in a web application since the connection to the database seldom is that long.

Just to update a single record in a single table, I would not use transactions, but if you har updating multiple tables, and those changes are connected to each other, and you need to make sure the changes are successful on all of them, then transactions is a good choice.

1 like
Snapey's avatar

Firstly, if at all possible, reengineer your solution to not need locks.

Using increment, decrement and upsert can avoid locks by using atomic methods.

If using locks, make sure you are using a fast cache like redis.

1 like

Please or to participate in this conversation.