PHP
Efficiently Create or Update Records with Eloquent `firstOrCreate` and `updateOrCreate`
Learn how to use Laravel Eloquent's `firstOrCreate` and `updateOrCreate` methods to atomically find a record or create it if it doesn't exist, or update it if it does.
use App\Models\Flight;
// Scenario 1: Find a flight by number and origin, or create it
$flight = Flight::firstOrCreate(
['flight_number' => 'AA123', 'origin' => 'JFK'], // Attributes to find by
['destination' => 'LAX', 'status' => 'scheduled'] // Attributes to create with
);
echo "Found/Created Flight ID: " . $flight->id . "
";
echo "Flight Status: " . $flight->status . "
"; // Will be 'scheduled' if created, existing status otherwise
// Scenario 2: Find a flight by number and origin, and update its status or create it
$flight = Flight::updateOrCreate(
['flight_number' => 'BA456', 'origin' => 'LHR'], // Attributes to find by
['destination' => 'ORD', 'status' => 'delayed', 'gate' => 'B23'] // Attributes to update or create with
);
echo "Updated/Created Flight ID: " . $flight->id . "
";
echo "Flight Status: " . $flight->status . "
"; // Will be 'delayed' if updated or created
// If an existing flight 'AA123' from 'JFK' exists, it will be returned without creating a new one.
// If a flight 'BA456' from 'LHR' exists, its destination, status, and gate will be updated. If not, it will be created.
How it works: The `firstOrCreate` method attempts to find a record matching the first array of attributes. If no record is found, it creates one using *both* the first array (for finding) and the second array (for additional creation attributes). `updateOrCreate` works similarly but will update the record with the second array of attributes if it finds a match, or create it using both arrays if not found. These methods are crucial for upsert operations, preventing race conditions by performing a find and create/update atomically.