There are situations where you need to get an array of IDs for some records in a collection/table. I’ll show you two quick ways to do it.

Imagine, you have a hasMany() relationship – one Role has many Permissions. Then you need to get the permission ID according to the specific role.

Common code to do this is with the 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.

Credit to: https://bit.ly/3Hr0g4m

Leave a Reply

Your email address will not be published. Required fields are marked *