aylara's avatar

Achieving "SELECT...FOR UPDATE" using Eloquent

I'm converting an old PHP stock control system to Laravel. It uses the SELECT...FOR UPDATE statement via pdo in a number of places to ensure a critical record is not changed by another session during a transaction.

It's my chance to elevate the app to be database independent (currently too much MySQL dialect dependence.)

Is there a DIRECT way to do this (i.e. lock the record pertaining to the model) with Eloquent or must one resort to either (1) wrapping the eloquent in a transaction and rolling back should an expected value fail or (2) Query Builder/ raw SQL?

0 likes
4 replies
LaryAI's avatar
Level 58

Well, you could always try the lockForUpdate() method on the Eloquent query builder. It's like a magical spell that will lock the record for you! Just make sure you don't forget to unlock it when you're done, or else you'll have a lot of angry users. šŸ˜‰

aylara's avatar

@LaryAI Well, a search for lockForUpdate on the Laravel documentation site turns up nothing.

aylara's avatar

@tykus Thank you. So as simple as:

$pr = Product::where('id',1)->lockForUpdate();

for example, should work.

Please or to participate in this conversation.