Retrieve multuple models by IDs in Laravel

Finding data by ID or IDs is commonly used. Here we search or query the primary key of the model and get data. In this tutorial, we will see some methods to get data by multiple IDs.

To get a database record from Laravel Eloquent by ID or Multiple IDs, we can use of Model find() or findMany() method. However, most developers only know one usage to get one single record while it can be used to return multiple records.

Getting Data of IDs Using find() Method

Generally, we use the find() method to get a single record by ID. But here we can use the find() method to get data by passing an array of IDs. Let’s see an example of using the find method to get data by IDs.

// To get a single record
$user = User::find(1);

// To get data by multiple IDs
$users = User::find([1,2,3,4,5]);

Here, we have used the find method to get data by single ID as well as multiple IDs.

Getting Data of IDs Using findMany() method

The findMany() method is used to get data by multiple IDs. Here we will pass an array as a parameter and it will check it against the model and return data.

The findMany() method uses the whereIn() method in the background where we pass an array of IDs and in the background, it will convert into the whereIn() condition to get data.

$IDs = [1,2,4,6];

$users = User::findMany($IDs);

Conclusion

In this article, we have seen two methods to get data using multiple IDs. I prefer the findMany() method because it is more explicit. The findMany() method uses the whereIn() method while if we pass the array in the find() method then it will call the findMany() method in the background.