From b5c636cc628151ff97073e80955bc3587ce642a7 Mon Sep 17 00:00:00 2001 From: Kevin Bui Date: Sat, 8 Nov 2025 20:53:23 +1100 Subject: [PATCH] Add the createOrFirst method. --- eloquent.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/eloquent.md b/eloquent.md index c8356bf2a1..d65830b9c8 100644 --- a/eloquent.md +++ b/eloquent.md @@ -706,6 +706,17 @@ $flight = Flight::firstOrNew( ); ``` +Alternately, we can also use the `createOrFirst` method, which will attempt to create a new record in the database first. If that fails because a unique index prevents duplicate values, the existing model will be returned. + +```php +// We try to create a new flight with the below number and name first. +// If that number already exists and has a unique index, the existing flight with that number will be returned. +$flight = Flight::createOrFirst( + ['number' => 'AA1234'], + ['name' => 'Chicago to Vancouver'] +); +``` + ### Retrieving Aggregates