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?
You can simply do
Model::all()->keyBy('category_id');
Cheers :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With