Tarasovych
Tarasovych

Reputation: 2398

Laravel's updateOrCreate function

I have such table | user_id | code | created_at | updated_at |.

I want to create a method, which creates a new one code (if it not exists) for specific user:

public function createCode(Request $request)
{
    $request->user()->confirmationCode()->updateOrCreate([
        'user_id' => $request->user()->id,
        'code' => bin2hex(random_bytes(3)),
    ]);
}

User model:

public function confirmationCode()
    {
        return $this->hasOne(ConfirmationCode::class);
    }

But createCode() always creates a new one code for user, even code for that user_id is already exists. What's wrong?

Upvotes: 0

Views: 690

Answers (1)

M31
M31

Reputation: 1418

Your syntax for updateOrCreate is incorrect. Currently to update it must match both of your inputs. You want the following:

public function createCode(Request $request)
{
    $request->user()->confirmationCode()->updateOrCreate(
        ['user_id' => $request->user()->id],
        ['code' => bin2hex(random_bytes(3))]
    );
}

The function matches on the first input array and then if found Updates with the values in the second array. If the matching fails it will create a new record with the values from both arrays.

https://laravel.com/docs/5.5/eloquent#other-creation-methods

Upvotes: 1

Related Questions