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 array of IDs.
Let's assume you are using HasMany relation and you need to check whether particular data is selected for that relationship or not. Like user can have much permission but on the user edit page you add a selection for permission and you need to check whether 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 in_array() method.
Here, we will get array of IDs using pluck() and modelKeys() method.
Below is general examples for 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 IDs of the primary key of the model otherwise it will show an error. Let's take 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.
In this article, we fetched IDs of model and collection using pluck() and modelKeys() method. The main difference between the pluck() and modelKeys() method is that modelKeys() method work only with the primary key while 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 primary key otherwise use pluck() method.
Ask anything about this examples