Reputation: 5509
Here is my code$titles = DB::table('roles')->lists('title');
How Can I cast $titles from a Laravel 5 collection into an associative array?
Upvotes: 1
Views: 1122
Reputation: 7083
Include the ID in the function, and call from the Model:
$titles = Role::lists('title', 'id')->toArray();
Or call directly as you are doing:
$titles = DB::table('roles')->lists('title', 'id');
In this case, in an select field for example, the id
will be the option value.
Upvotes: 4
Reputation: 14620
A laravel collection has a toArray
method that will return a numerically keyed array of the contents. (The indexes will be keyed exactly as they are in the collection. To reset them call values
on the collection first.)
$titles = DB::table('roles')->lists('title');
$result = $titles->toArray();
For an associative array you will need to do this manually using something like this.
$titles = DB::table('roles')->lists('title', 'id');
$result = [];
foreach($titles as $title) {
// using an ID as the key and title as the value
$result[$title->id] = $title->title;
}
Upvotes: 2