Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent: Return Array key as the fields ID

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

like image 372
Broshi Avatar asked Nov 11 '14 13:11

Broshi


2 Answers

You can simply do

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

Cheers :)

like image 188
Bhoj Raj Bhatta Avatar answered Sep 18 '22 19:09

Bhoj Raj Bhatta


Since you have an Eloquent Collection (a child class of the generic Collection class) you can use the getDictionary method. $collection->getDictionary() will give you an array of your Category objects keyed by their primary keys.

If you wanted another Collection rather than a native PHP array, you could instead use $collection->keyBy($property). It looks like your primary key is category_id, so $collection->keyBy('category_id'). You can use that method to key by any arbitrary property, including any get mutators you may have written.

While getDictionary is unique to the Eloquent Collection extension, keyBy is available to all Laravel Collection objects. See the Laravel 4.2 API docs or Laravel 5.0 API docs.

like image 45
tremby Avatar answered Sep 20 '22 19:09

tremby