DEV Community

Vishnu Damwala
Vishnu Damwala

Posted on

4

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 ๐Ÿ‡ฎ๐Ÿ‡ณ

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay