PHP
Simplify Upsert Operations with Eloquent `firstOrCreate` and `updateOrCreate`
Efficiently retrieve or create a model with `firstOrCreate`, and update or create a model with `updateOrCreate`, streamlining common database upsert operations in Laravel.
// In a controller or service
use App\Models\Flight;
// firstOrCreate: Find a flight, or create it if not found.
// The first array contains attributes to find by.
// The second array contains attributes to set if creating.
$flight = Flight::firstOrCreate(
['name' => 'Flight ABC'],
['destination' => 'New York', 'departure' => '2024-07-01']
);
// If 'Flight ABC' exists, it's returned. If not, a new flight is created
// with name 'Flight ABC', destination 'New York', and departure '2024-07-01'.
// updateOrCreate: Find a flight, or create it if not found.
// If found, update its attributes. If not found, create it.
$updatedFlight = Flight::updateOrCreate(
['name' => 'Flight XYZ'], // Attributes to find by
['destination' => 'London', 'departure' => '2024-08-15', 'status' => 'scheduled'] // Attributes to create/update
);
// If 'Flight XYZ' exists, its destination, departure, and status are updated.
// If not, a new flight is created with all provided attributes.
// Example with existing record
// Assume a flight 'Flight ABC' exists from the first example.
$flightToUpdate = Flight::updateOrCreate(
['name' => 'Flight ABC'],
['destination' => 'Paris', 'status' => 'delayed']
);
// 'Flight ABC' is found, its destination is updated to 'Paris' and status to 'delayed'.
// The 'departure' attribute (if it existed) would remain unchanged unless specified.
How it works: The `firstOrCreate` method attempts to find a record matching the first array of attributes. If found, it returns the model instance. If not, it creates a new record with both the first and second array of attributes. `updateOrCreate` works similarly but also updates the attributes in the second array if a matching record is found, effectively performing an "upsert" operation. Both methods are highly useful for preventing duplicate records and streamlining data management when you need to ensure a record exists and has specific attributes.