'Laravel Eloquent get() indexed by primary key id

I often find it very useful to index my results by the primary key id.

Example:

$out = [];

$users = User::where('created_at', '>=', '2015-01-01')->get();

foreach ($users as $user) {
    $out[$user->id] = $user;
}

return $out;

Is there anyway to do this in one shot with Eloquent? It's not useful to use the 0...n index.



Solution 1:[1]

You can accomplish this by using getDictionary() on your collection.

Like so:

$users = User::where('created_at', '>=', '2015-01-01')->get()->getDictionary();

Note: in newer version of Laravel (5.2+), getDictionary() was removed; keyBy() can be used instead:

$users = User::where('created_at', '>=', '2015-01-01')->get()->keyBy('id');

Solution 2:[2]

I created my own solution by having a super Model that extends Eloquent.

Full solution: https://gist.github.com/yadakhov/741173ae893c1042973b

/**
 * Where In Hashed by primary key
 *
 * @param array $ids
 * @return array
 */
public static function whereInHash(array $ids, $column = 'primaryKey')
{
    $modelName = get_called_class();
    $primaryKey = static::getPrimaryKey();
    if ($column === 'primaryKey') {
        $column = $primaryKey;
    }
    $rows = $modelName::whereIn($column, $ids)->get();
    $out = [];
    foreach ($rows as $row) {
        $out[$row->$primaryKey] = $row;
    }
    return $out;
}

Solution 3:[3]

Not with eloquent but this is potentially nicer option than looping through all the results.

$users = Users::all();

return array_combine($users->modelKeys(), $users);

Solution 4:[4]

You can use keyBy()

$users = User::where('created_at', '>=', '2015-01-01')->get()->keyBy('id')->toArray();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DisgruntledGoat
Solution 2 Yada
Solution 3 Wader
Solution 4 Sachin Sarola