Inserting & Updating Models: Other Creation Methods

FirstOrCreate/ firstOrNew

// 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]
);

// Retrieve by name, or instantiate...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);

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

The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes.

UpdateOrCreate

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

You may also come across situations where you want to update an existing model or create a new model if none exists.

Inserting & Updating Models: Other Creation Methods — Structure map

Clickable & Draggable!

Inserting & Updating Models: Other Creation Methods — Related pages: