Eloquent column list by key with array as values?

So I can do this with Eloquent:

$roles = DB::table('roles')->lists('title', 'name');

But is there a way to make Eloquent fetch an array of values for each distinct key instead of just one column?

For instance, something like the following:

$roles = DB::table('roles')->lists(['*', DB:raw('COALESCE(value, default_value)')], 'name');

Answers


You can use the keyBy method:

$roles = Role::all()->keyBy('name');

If you're not using Eloquent, you can create a collection on your own:

$roles = collect(DB::table('roles')->get())->keyBy('name');

If you're using Laravel 5.3+, the query builder now actually returns a collection, so there's no need to manually wrap it in a collection again:

$roles = DB::table('roles')->get()->keyBy('name');

If you need a key/value array, since Laravel 5.1 you can use pluck. This way you can indicate which attributes you want to use as a value and as a key.

$plucked = MyModel::all()->pluck('MyNameAttribute', 'MyIDAttribute');

return $plucked->all();

You will get an array as follow:

array:3 [▼
   1 => "My MyNameAttribute value"
   2 => "Lalalala"
   3 => "Oh!"
]

You may try something like this:

$roles = array();
array_map(function($item) use (&$roles) {
    $roles[$item->id] = (Array)$item; // object to array
}, DB::table('roles')->get());

If you want to get an Object instead of an Array as value then just remove the (Array).

Alternative: Using Eloquent model (Instead of DB::table):

$roles = array();
array_map(function($item) use (&$roles) {
    $roles[$item['id']] = $item;
}, Role::all()->toArray());

Another Alternative: Using Collection::map() method:

$roles = array();
Role::all()->map(function($item) use(&$roles) {
    $roles[$item->id] = $item->toArray();
});

Need Your Help

how to debug with xUnit?

c# .net unit-testing debugging xunit

I'm learning xUnit and so far, have found it to be a most useful tool. It's making me rethink some of my coding tactics to TDD instead.

beginBackgroundTaskWithExpirationHandler never gets called

iphone objective-c ios background-process uiapplication

I have an app that plays audio in the background. I'm trying to use beginBackgroundTaskWithExpirationHandler to skip to the next track when the current track is finished.