Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Apr 22, 2022
Merged

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

merged 2 commits into from
Apr 22, 2022

Conversation

jessarcher
Copy link
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
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

mreduar commented Apr 27, 2022

Nice!

@novalramdhani
Copy link

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

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