firstOrNew
$user = User::where('email', request('email'))->first();
if ($user === null) {
$user = new User(['email' => request('email')]);
}
$user->name = request('name');
$user->save()
// firstOrNew--------------------------------------
$user = User::firstOrNew(['email' => request('email')]);
$user->name = request('name');
$user->save()
$user = User::firstOrNew(
['email' => request('email')],
['name' => request('name')]
);
$user->save();
firstOrCreate
$user = User::firstOrCreate(
['email' => request('email')],
['name' => request('name')]
);
// No call to $user->save() needed
firstOr
$user = User::where('email', request('email'))->firstOr(function () {
$account = Account::create([ //... ]);
return User::create([
'account_id' => $account->id,
'email' => request('email'),
]);
});
updateOrCreate
$user = User::where('email', request('email'))->first();
if ($user !== null) {
$user->update(['name' => request('name')]);
} else {
$user = User::create([
'email' => request('email'),
'name' => request('name'),
]);
}
// Do other things with the User
$user = User::updateOrCreate(
['email' => request('email')],
['name' => request('name')]
);
// Do other things with the User