Laravel Tip: firstWhere() vs where()->first() – Which One Should You Use?
When working with Eloquent in Laravel, you’ve likely come across two ways to fetch the first matching model from the database:
Currency::where('code', 'CAD')->first();
or
Currency::firstWhere('code', 'CAD');
At first glance, they seem interchangeable—and for the most part, they are. But let’s break them down to understand the nuances and choose the right tool for the right situation.
🆚 The Comparison
where()->first()
This has been around since the early days of Laravel. It’s straightforward and widely used:
Currency::where('code', 'CAD')->first();
- Highly flexible – you can chain multiple
where()
conditions,orderBy()
,with()
, scopes, etc. - Familiar syntax – used throughout Laravel documentation and many community examples.
- Ideal for building dynamic queries.
firstWhere()
Introduced in Laravel 6 for Collections and added to Eloquent in Laravel 8:
Currency::firstWhere('code', 'CAD');
- Clean and concise – perfect for simple filters.
- Reduces boilerplate when all you need is the first match on a single field.
- Slightly more readable, especially for newcomers or one-liner code.
🧩 When to Use Which?
Here’s a simple rule of thumb:
Use Case | Prefer |
---|---|
Single simple condition | firstWhere() |
Multiple conditions | where()->first() |
Need orderBy , limit , scopes |
where()->first() |
Just want clarity and quick lookup | firstWhere() |
🤔 Other Considerations
- Readability matters. If your project or team prioritizes brevity and expressive code,
firstWhere()
might be your go-to. - Consistency is also important. If your codebase predominantly uses one style, it may be best to stick with it unless there’s a compelling reason to switch.
- Chaining with Eloquent scopes (e.g.,
->active()
) only works withwhere()
style.firstWhere()
does not support chaining.
If you're using dynamic field names, where()->first()
gives you better control:
$field = 'code';
Currency::where($field, 'CAD')->first();
📝 Finally
Both methods do the job. But like most things in Laravel, elegance lies in intention. If you’re fetching something quickly with minimal logic, firstWhere()
is your friend. If you’re crafting a more robust or reusable query, stick with where()->first()
.
Pick the right tool for the job, and your code will thank you.
Comments ()