micky
micky

Reputation: 317

FirstOrCreate with only some attributes

I want to create a user if not matched:

$newUser=User::firstOrCreate(array('name' => $user->name, 'email' => $user->email,'avatar'=>$user->avatar));

But, i also need to store token which will be different every time even if other attributes matches. So, i need something like match with only name, email, avatar but also store or update token.

Upvotes: 1

Views: 388

Answers (2)

Saumya Rastogi
Saumya Rastogi

Reputation: 13703

You can do it in this way:

$newUser = User::firstOrCreate([
    'name' => $user->name,
    'email' => $user->email,
    'avatar' => $user->avatar
]);

$newUser->token = bin2hex(openssl_random_pseudo_bytes(16));

$newUser->save();

Hope this helps!

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163848

Pass an array of additional values as second parameter:

$newUser = User::firstOrCreate(
    ['name' => $user->name, 'email' => $user->email, 'avatar' => $user->avatar],
    ['token' => $token]
);

To understand how it works look at source code of firstOrCreate() method.

Upvotes: 1

Related Questions