Skip to main content
Tutorial Free

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

August 08, 2019
2 min read

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

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

How to Build Laravel 12 API From Scratch

28 lessons
1 h 21 min

NativePHP: Build Mobile App with Laravel

11 lessons
2 h 2 min read

Laravel HTTP Client and 3rd-Party APIs

7 lessons
50 min

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.