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();

Note : The firstOrNew() method will get the first instance if it exists in the table or makes a new model instance but it will not save model instance implicitly. You need to explicitly save model instance with save() method

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳