Get Array of IDs from Eloquent Collection: pluck() or modelKeys()

There are situations where you need to get array of IDs for some records in collection/table. I will show you two quick ways to do it – one is pretty popular, and another is a function which I found out only today.

Imagine, that you have hasMany() relationship – one Role has many Permissions. And then you need to get IDs of permission by a certain role.

Typical code to do this will be with pluck() function:

// returns array of IDs
$permissionIDs = $role->permissions->pluck('id'); 

But what if your auto-increment primary key name is not “id”? Apparently, you can get the key(s) from Laravel model, with method modelKeys() on Collection:

// Same result as above. Even same character count :)
$permissionIDs = $role->permissions->modelKeys();

Official description of modelKeys() method is pretty short: “Get the array of primary keys.”

Notice that, as I said before, it works on Collections, not on just Laravel model. So method pluck() exists for both Model and Collection, so both would work:

$allPermissions = Permission::pluck('id');
$permissions = $role->permissions->pluck('id');

But in case of modelKeys(), this will fail with error “Call to undefined method App\Permission::modelKeys()”:

$allPermissions = Permission::modelKeys();

The workaround is to get all results into Collection and then get the keys:

$allPermissions = Permission::all()->modelKeys();

But it may cause performance issues if you’re getting all records for big table.

So, just a quick tip on modelKeys() method I’ve learned only now, more like “interesting to know” than actually practical in everyday projects 🙂

Like our articles?
Check out our Laravel online courses!

LEAVE A REPLY

Please enter your comment!
Please enter your name here