Eloquent column list by key with array as values?

eComEvo picture eComEvo · Jun 10, 2014 · Viewed 74.8k times · Source

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');

Answer

Joseph Silber picture Joseph Silber · Jun 10, 2014

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');