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

JohanCorn's avatar

Relationship lockForUpdate

Is it possible to use "lockForUpdate" with relationship in a transaction?

This is working.

$something = Something::lockForUpdate()->firstOrCreate(['user_id' => $user->id]);

This one is not.

$something = $user->something()->lockForUpdate()->firstOrCreate();

Relation in User.php

    public function something()
    {
        return $this->hasOne(Something::class);
    }

Note: Both methods working without lockForUpdate().

0 likes
1 reply
kevinbui's avatar
kevinbui
Best Answer
Level 41

I have read the source code. The lockForUpdate method is part of the Illuminate\Database\Query\Builder class, and will return an instance of that class.

Therefore, you can use that method with a relationship and a model class, and the followings are gonna work:

Something::where(...)
    ->lockForUpdate()
    ->get();

$user->something()
    ->lockForUpdate()
    ->get();

$user->something()
    ->where(...)
    ->lockForUpdate()
    ->get();

firstOrCreate or any other updating methods cannot be used, because those records are locked. Plus, firstOrCreate method does not belong to the Illuminate\Database\Query\Builder class.

1 like

Please or to participate in this conversation.