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.
$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.
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.
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.
findMany()
communicates your intent more clearly.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.