Laravel Eloquent: Return Array key as the fields ID

Broshi picture Broshi · Nov 11, 2014 · Viewed 43.9k times · Source

When I execute a query via Laravel's Eloquent ORM, I want to get the row ID as the Array result key, this will make things easier when I want to check something based on an ID (using array_key_exists) or do some look ups (if I need a specific entry from the result array)

Is there any way I can tell Eloquent to set the key to the fields ID? see image

Answer

Bhoj Raj Bhatta picture Bhoj Raj Bhatta · Feb 6, 2016

You can simply do

Model::all()->keyBy('category_id');

Cheers :)