Laravel's firstOrCreate Model Method

cooldashing24

Vishnu Damwala

Posted on December 25, 2020

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 = [])
Enter fullscreen mode Exit fullscreen mode
  • 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();
Enter fullscreen mode Exit fullscreen mode

Example with firstOrCreate()

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

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

$device->save();
Enter fullscreen mode Exit fullscreen mode

Read the complete post on our site Laravel's firstOrCreate Model Method

Read others post on our site MeshWorld

Happy 😄 coding

With ❤️ from 🇮🇳

💖 💪 🙅 🚩
cooldashing24
Vishnu Damwala

Posted on December 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related