Laravel's firstOrCreate Model Method

While working on an application, you might have a need, initially to search from the table for an instance. And if it does not exists you need to explicitly create a new record and save in the table. Laravel provides a method firstOrCreate() which comes handy, that performs both actions, searching or creating new and return that instance. So that you can just start working with it. This method is worth using.

In this article, we will see an example of firstOrCreate(), a similar one like firstOrNew()( that retrieves the first instance if it exists or creates a new model instance without saving actually in the table).

firstOrCreate()

The firstOrCreate() method helps to find the first model that matches the specified constraints or create a new model instance one if does not exists with the matching constraints.

Syntax

  Model::firstOrCreate(array $attributes = [], array $values = [])
  • It gets the first record matching the attributes or create a new one
  • It searches the model with the matching attributes that are passed as the first parameter
  • If a matching model is not found, it creates and saves a new Model after applying any key-value pair passed as the second parameter

Example without firstOrCreate()

$uuid = request('uuid');
$device = Device::where('uuid', $uuid)->first();

if ($device === null) {
  $device = new Device(['uuid' => $uuid]);
}

$device->operating_system = request('operatingSystem');
$device->version = request('version');

$device->save();

Example with firstOrCreate()

$device = Device::firstOrCreate('uuid', request('uuid'));

$device->operating_system = request('operatingSystem');
$device->version = request('version');

$device->save();

The firstOrCreate() method also accepts attributes as a second parameter for initializing model attributes if an existing model is not found.

$device = Device::firstOrCreate(
  ['uuid' =>  request('uuid')],
  [
    'operating_system' => request('operatingSystem')
    'version' => request('version')
  ]
);

$device->save();

Both firstOrCreate and firstOrNew methods are very similar.

Note: The firstOrCreate() method will get the first instance if it exists in the table or creates a new model, saving it in the table implicitly

How to find or create a new record if it does not exists

Keep helping and happy 😄 coding

Vishnu Damwala
Vishnu Damwala

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