Laravel Eloquent: Return Array key as the fields ID

PhpLaravelEloquent

Php Problem Overview


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

Php Solutions


Solution 1 - Php

You can simply do

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

Cheers :)

Solution 2 - Php

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.

Solution 3 - Php

You have a Support\Collection/Database\Eloquent\Collection you can use the method lists('id') to return an array of the id of each of the models within the collection.

Then use array_combine to map the keys to the models. The result of which will be an array with the id mapped to their corresponding model.

Solution 4 - Php

If you need id as the key, then rely on the Collection:

$collection = Model::all();

$collection->getDictionary();

// returns:
array(
  1 => object(Model) ( ... ),
  2 => object(Model) ( ... ),
  ...
  idN => object(Model) ( ... )
);

Otherwise, nice or not, you can do this:

$keys = $collection->lists('columnName');

$arrayOfModels = array_combine($keys, $collection->getDictionary);

Solution 5 - Php

pluck('label','id') on the get() output is what you're looking for in Laravel 5.8+, which gives you a collection, ready to be toArray()ed

eg:

$options = \App\DataChoice::where([ 'field_id' => $dataField->id , 'active' => true ])->get()->pluck('label','id')->toArray();

I had a similar challenge - I wanted to a PHP array to allow me to create a

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBroshiView Question on Stackoverflow
Solution 1 - PhpBhoj Raj BhattaView Answer on Stackoverflow
Solution 2 - PhptrembyView Answer on Stackoverflow
Solution 3 - PhpMatt BurrowView Answer on Stackoverflow
Solution 4 - PhpGeorge JohnView Answer on Stackoverflow
Solution 5 - PhpNULL pointerView Answer on Stackoverflow