Skip to content

[9.x] Add a findOr method to Eloquent#42092

Merged
taylorotwell merged 2 commits into9.xfrom
eloquent-find-or
Apr 22, 2022
Merged

[9.x] Add a findOr method to Eloquent#42092
taylorotwell merged 2 commits into9.xfrom
eloquent-find-or

Conversation

@jessarcher
Copy link
Copy Markdown
Member

@jessarcher jessarcher commented Apr 22, 2022

This PR adds a findOr() method to the Eloquent Builder and Relations. This matches the existing firstOr() methods.

A typical scenario where this method is useful is when a resource route (e.g. /posts/1) cannot find a model that is not part of the URL, and so a findOrFail() returning a 404 is not appropriate.

Example usage:

User::findOr(1, fn () => throw new RuntimeException);
User::findOr(1, fn () => abort(403));
User::findOr(1, fn () => 'return something');

The method also supports passing columns as the second argument:

User::findOr(1, ['columns'], fn () => '...');

It also works on HasMany, HasManyThrough, BelongsToMany, MorphMany, and MorphToMany relations:

$user->posts()->findOr(1, fn () => '...');

@BrandonSurowiec
Copy link
Copy Markdown
Contributor

Neat idea. Has some overlap use-case wise with Route::missing() that was added in 8.x: #36035

@taylorotwell taylorotwell merged commit b062355 into 9.x Apr 22, 2022
@taylorotwell taylorotwell deleted the eloquent-find-or branch April 22, 2022 14:40
@mreduar
Copy link
Copy Markdown

mreduar commented Apr 27, 2022

Nice!

@novalramdhani
Copy link
Copy Markdown

Great feature!!!

@GrahamCampbell GrahamCampbell changed the title Add a findOr method to Eloquent [9.x] Add a findOr method to Eloquent Apr 30, 2022
@Technoyer
Copy link
Copy Markdown

This method adds some flexibility instead of findOrFail() we can now handle the fail output using whatever callback.
@jessarcher congratulations for the great work.

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.

6 participants