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

Anour's avatar
Level 1

Pessimistic Locking

I can't understand some things about subject from the docs.

  1. What should I do to unlock records (table) after lockForUpdate() or sharedLock() ?

  2. Does lock make any sense if record not exists? For example:

$model = \App\Table::where('field', '=', $value)->lockForUpdate()->first(); // will it prevent duplicates?
if (!$model) {
     $model= \App\Table::create(['field' => $value]);
} else {
    $model->touch();
}
0 likes
5 replies
Anour's avatar
Level 1

@gregrobson It is a useful thread. Thanks for that.

Lock for Update and Transactions are two separate things. You do not need to wrap it in a transaction.

If it is true, how can I unlock the records without transaction?

Anour's avatar
Level 1

Is there any way to lock the whole table?

lock tables `table` WRITE

for MySQL (for example)

gregrobson's avatar

I believe the tables will be unlocked at the end of the session (once Laravel cleans up at the end of processing the request).

You can lock tables with MySQL http://dev.mysql.com/doc/refman/5.7/en/lock-tables.html ... although that should only be done in very special situations. Locking an entire table can slow up all other queries trying to use the table.

Most of the time you shouldn't need to worry about locking - the database is normally good at handling this. The cases where you might want to lock a table are when you have a requirement that no two processes get an inconsistent snapshot of the data. Unless you have a high volume database (1000s of queries/second) that would be rare.

If you just have a basic application (a few dozen users) it's unlikely you will need to lock for update, as the whole request will be over in milliseconds. Be wary of premature optimisation!

Anour's avatar
Level 1

@gregrobson

Thanks for your answers. I guess, now I understand the Laravel's philosophy of locks.

Please or to participate in this conversation.