Laravel's firstOrNew Model Method
Laravel provides methods other than standard methods. You might be familiar with make(), create(), save() or update(). And these methods are worth using.
In this article, we will see firstOrNew(), one of the model method that comes handy when you want to get the first instance if it exists or create a new model instance.
firstOrNew()
The firstOrNew() method helps to find the first model that matches the specified constraints or making a new model instance one if does not exists with the matching constraints.
Example without firstOrNew()
$email = request('email');
$user = User::where('email', $email)->first();
if ($user === null) {
$user = new User(['email' => $email]);
}
$user->username = request('username');
$user->save();
Example with firstOrNew()
$user = User::firstOrNew('email', request('email'));
$user->username = request('username');
$user->save();
The firstOrNew() method also accepts attributes as a second parameter for initializing model attributes if an existing model is not found.
$user = User::firstOrNew(
['email' => request('email')],
['username' => request('username')]
);
$user->save();