Camkode
Camkode

Laravel Tip: Use findMany() Instead of whereIn()->get() for Cleaner Code

Posted by Kosal

When working with Laravel's Eloquent ORM, readability and expressiveness go a long way in writing clean, maintainable code. A common task in many applications is retrieving multiple records by their IDs. While there are multiple ways to achieve this, not all are equally clean or intention-revealing.

Let’s look at a simple example and how you can improve it.

❌ Before: The Verbose Way

$users = User::whereIn('id', [1, 2, 3])->get();

This works perfectly fine and is very common among developers, especially those coming from raw SQL or query builder backgrounds. However, it’s a bit verbose for such a common operation, and it doesn't clearly convey the intent of fetching records by ID.

✅ After: Use find()

$users = User::find([1, 2, 3]);

Laravel's Eloquent find() method is designed to retrieve a record by primary key. Conveniently, when you pass it an array, it fetches multiple records in one query. This approach is cleaner and easier to understand at a glance.

✅ Even Better: Use findMany()

$users = User::findMany([1, 2, 3]);

findMany() is functionally identical to find() when passed an array, but it's more expressive. By using findMany(), you're explicitly telling other developers (or your future self) that you're working with multiple records. This subtle semantic clarity improves code readability and intention.

Why It Matters

  • Readability: Code is read more often than it is written. Using expressive methods like findMany() communicates your intent more clearly.
  • Consistency: Using Eloquent methods designed for specific purposes ensures a consistent and idiomatic Laravel codebase.
  • Maintainability: Cleaner, intention-revealing code is easier to debug, refactor, and enhance.

Final Thoughts

When writing Laravel applications, always aim for clarity and purpose in your code. Using findMany() over whereIn()->get() is a small change, but it reflects a bigger mindset—writing code that speaks for itself.