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

[11.x] Add Eloquent\Collection::findOrFail #52690

Merged

Conversation

stevebauman
Copy link
Contributor

Description

This PR adds a way to find a model in a collection (or throw an exception) with an already populated Eloquent collection.

Having this method available is handy in edge-case circumstances, and is also a nice to have for feature parity with the core Support\Collection instance (as it sports its own findOrFail method).

Usage

$users = User::get(); // [User(id: 1), User(id: 2)]

$users->findOrFail(1); // User

$user->findOrFail([]); // []

$user->findOrFail([1, 2]); // [User, User]

$user->findOrFail(3); // ModelNotFoundException: 'No query results for model [User] 3'

$user->findOrFail([1, 2, 3]); // ModelNotFoundException: 'No query results for model [User] 3'

Empty Collection Behaviour:

Since no models exist in the collection, there will be no message set, since a model cannot be determined.

$users = User::get(); // []

$users->findOrFail(); // ModelNotFoundException: ''

@taylorotwell taylorotwell merged commit fc4918d into laravel:11.x Sep 9, 2024
33 checks passed
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