Skip to content

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants