How to lock table with Laravel?

One can lock a table in Laravel like this:

DB::raw('LOCK TABLES important_table WRITE');


As pointed out in the comments by other users too, I don't feel certain that a table lock is absolutely the only way out. However, if you insist, you could use Laravel's Pessimistic Locking. Namely, sharedLock() and lockForUpdate() methods, as mentioned in the documentation.

You'd notice that the example in the documentation doesn't use Eloquent, but relies on Query Builder. However, this Q&A seems to suggest that it can be done with Eloquent too.

It may also be worthwhile to have a read through this article which contrasts Pessimistic and Optimistic locking implementations in Laravel.