laravelhashmapeloquent

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

  • In Laravel 5.1 this could be accomplished 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');