Skip to content

Comments

[12.x] Allow closures for values in firstOrCreate and createOrFirst#58639

Merged
taylorotwell merged 1 commit intolaravel:12.xfrom
gcavanunez:gc/adds-closure-support-to-first-or-create
Feb 5, 2026
Merged

[12.x] Allow closures for values in firstOrCreate and createOrFirst#58639
taylorotwell merged 1 commit intolaravel:12.xfrom
gcavanunez:gc/adds-closure-support-to-first-or-create

Conversation

@gcavanunez
Copy link
Contributor

@gcavanunez gcavanunez commented Feb 5, 2026

This PR allows firstOrCreate & createOrFirst to accept a closures as the $values parameter, so that lazy evaluation of expensive operations are only happening when a record actually needs to be created.

The use case

When using firstOrCreate with values that involve expensive operations (API calls, encryption) are evaluated eagerly, even when the record already exists and the values are never used.

To work around this today, you have to leave firstOrCreate and split the lookup from the creation:

$location = Location::query()->firstWhere('address', $address);

if ($location) {
    return $location;
}

return Location::create([
    'address' => $address,
    'coordinates' => Geocoder::resolve($address),
]);

With this PR, you can wrap the values in a closure to defer evaluation while preserving the single call:

$location = Location::firstOrCreate(
    ['address' => $address],
    fn () => ['coordinates' => Geocoder::resolve($address)],
);

@taylorotwell taylorotwell merged commit 6ce926d into laravel:12.x Feb 5, 2026
72 checks passed
GromNaN added a commit to mongodb/laravel-mongodb that referenced this pull request Feb 11, 2026
…3479)

Declare Query\Builder::timeout() conditionally if not declared in Laravel.
Added timeout method to query builder for MySQL laravel/framework#58644

Support value-closure as 2nd argument of createOrFirst and firstOrCreate.
Allow closures for values in firstOrCreate and createOrFirst laravel/framework#58639
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants