Laravel Eloquent: Return Array key as the fields ID

Laravel Questions editorial team
Editorial team · 5 July 2026

A query returns a list indexed 0, 1, 2. You want the array keys to be the record ids instead.

keyBy('id')

$users = DB::table('users')->get()->keyBy('id');

$users[8]->name; // the user whose id is 8

With Eloquent it is the same call on the result: User::all()->keyBy('id'). Keep the whole record, indexed by id.

pluck('name', 'id')

When you only need one value per id, the second argument of pluck is the key:

User::pluck('name', 'id');
// [5 => 'Ana', 8 => 'Bo', 12 => 'Cy']

It selects just those two columns, so it is lighter than loading whole models.

mapWithKeys

For any other key or value, return a one-pair array from the callback:

$map = User::get()->mapWithKeys(fn ($user) => [$user->id => strtoupper($user->name)]);
// [5 => 'ANA', 8 => 'BO', 12 => 'CY']

JSON gotcha

Keys that are not 0, 1, 2 in order turn into a JSON object:

User::pluck('name', 'id')->toJson();          // {"5":"Ana","8":"Bo","12":"Cy"}
User::pluck('name', 'id')->values()->toJson(); // ["Ana","Bo","Cy"]

Call values() if the front end expects a plain array. Keep the keyed form if it expects a lookup by id.

Tested on Laravel 10.x (PHP 8.1) and 12.x (PHP 8.3) with SQLite: the tests use ids 5, 8 and 12 and check the keys, pluck, mapWithKeys and both JSON shapes. Source: tests/laravel-verification/files/q1532.

Our network