简体   繁体   中英

Laravel's updateOrCreate function

I have such table | user_id | code | created_at | updated_at | | 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM