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

Tutorial last revisioned on August 18, 2022 with Laravel 9

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\Models\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 :)

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1188 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses