Get array of ids from eloquent collection or model in Laravel

Sometimes we need to get an array of database results or collection IDs. There are many ways to get this output like using loops or array functions. But the pluck() and modelKeys() methods are proper to get an array of IDs.

Let’s assume you are using a HasMany relation and you need to check whether particular data is selected for that relationship or not. Like user can have many permissions but on the user edit page you add a selection for permission and you need to check whether a particular permission is enabled for a user or not. In this example, if you have an array of user-enabled permission then you can easily use the in_array() method.

Here, we will get an array of IDs using the pluck() and modelKeys() methods.

Below is general examples of the pluck method:

//Gets all permission IDs
$allPermissions = Permission::pluck('id');
$role = Role::find(1);

//On Model
$permissionIds = $role->permissions->pluck('id');

//On collection
$permissions = $role->permissions;
$permissionIds = $permissions->pluck('id');

The modelKeys() method is used when we want to get the IDs of the primary key of the model otherwise it will show an error. Let’s take an example for the modelKeys() method :

$allPermissions = Permission::modelKeys();

$permissionIds = $role->permissions->modelKeys();

While using the modelKeys() method, there is no need to pass the key name. Whereas, with the pluck method, you can choose the particular column to convert the array.

Conclusion

In this article, we fetched the IDs of the model and collection using the pluck() and modelKeys() methods. The main difference between the pluck() and modelKeys() method is that modelKeys() method works only with the primary key. However, the pluck() method works with any field of table or collection.

As per the above example, it’s idle to use modelKeys() method while getting the primary key otherwise use the pluck() method.