Home / Blog /

Return primary keys from Eloquent Collections: the simple way

3 years ago

Return primary keys from Eloquent Collections: the simple way

I have been using Laravel for a while now, and every so often I run into a new little trick to make life easier. Today I wanted to share a discovery I made a couple of years ago, that simplified slightly.

👀 352 views

I was writing a lot of tests at the time. The same pattern was repeated:

$primaryKeysArray = Model::where('something', 'something')
    ->get()->pluck('primaryKey')
    ->toArray();

At that time, I did not question this approach, thinking it would be one of the quickest ways to get this done.

Only later did I discover the function:
 
modelKeys() 

The modelKeys method returns the primary keys for all models in the collection, AND making it an array. Above example can be simplified to:

$primaryKeysArray = Model::where('something', 'something')
    ->get()
    ->modelKeys();

Pretty nifty right?