-
Notifications
You must be signed in to change notification settings - Fork 11k
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
[6.x] Add ->firstWhere eloquent method #31089
[6.x] Add ->firstWhere eloquent method #31089
Conversation
An added benefit here is that when using Laravel IDE-helpers, your IDE can understand what type is being returned: // Before:
/** @var User $user */
$user = User::where('email', '[email protected]')->first();
// After:
// IDE knows the type without an annotation
$user = User::firstWhere('email', '[email protected]'); |
Might want to shoot a PR to the docs too. <3 |
Done: laravel/docs#5716 |
Good to have it, but what about using traditional collection
I know Enumerable has |
It doesn't work the same, the new method will give an instance of the model based on It seems to me that's working like this |
Right @mbougarne , but that method could be simply improved by checking argument number for example. If we have more than 1 argument, than we assume we passed a condition -> so it will return the first entry matching that condition. The benefit is that we maintain the collection pattern. |
after using this more and more I'm finding myself wanting a I can create a PR if anyone else might find it useful. |
A shortcut for
->where(...)->first()
Example: I'm fetching a user by email address:
My initial instinct was
->whereFirst
, but 1. it's a breaking change, and 2. collections have a->firstWhere
.Implementation Notes:
I only added this to the Eloquent builder for now. I thought I could just add it to the Query builder and everything would be fine, but I ran into some issues (the test I wrote was failing).
If it turns out people want this on the Query builder itself, could just copy it there. (or dig into the root problem, which probably has something to do with me not understanding the forwarding chain (and it's implications) well enough.
Thanks!