Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sohomdeep's avatar

Difference between firstOrCreate and create

What is the difference between firstOrCreate and create in Eloquent model. Which is better to use, Means which is optimized and good practice.

0 likes
2 replies
staudenmeir's avatar

As the name says, firstOrCreate() only creates an item if it doesn't already exist. create() always creates one.

Cronix's avatar

The docs aren't clear on this?

The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the attributes from the first parameter, along with those in the optional second parameter.

// Retrieve flight by name, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);

// Retrieve flight by name, or create it with the name and delayed attributes...
$flight = App\Flight::firstOrCreate(
    ['name' => 'Flight 10'], ['delayed' => 1]
);

https://laravel.com/docs/5.7/eloquent#other-creation-methods

1 like

Please or to participate in this conversation.