1

Here is my code
$titles = DB::table('roles')->lists('title');
How Can I cast $titles from a Laravel 5 collection into an associative array?

Laerte
  • 7,013
  • 3
  • 32
  • 50
Salar
  • 5,305
  • 7
  • 50
  • 78

2 Answers2

4

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.

Laerte
  • 7,013
  • 3
  • 32
  • 50
  • the result is still a laravel collection, I want to cast this collection into a PHP associative array. – Salar Feb 03 '16 at 13:09
  • 1
    Try to call `toArray()` in the collection result. – Laerte Feb 03 '16 at 13:25
  • As far as I can tell, Laravel does not contain a `lists` method anywhere which returns a `Collection`, hence `toArray` should not be necessary and would result in a fatal error for anyone else. Are you overriding some functions somewhere? – user1669496 Feb 03 '16 at 14:01
  • Actually, you are right @user3158900. I've changed my answer again. – Laerte Feb 03 '16 at 14:11
  • How to convert back "toArray()" into normal eloquent model ? Is it possible ? – Ephra May 07 '18 at 20:01
  • @Ephra I don't think there is a function that does exactly this, but you can try to use `whereIn` with the IDs. Take a look here: https://stackoverflow.com/questions/30706603/laravel-whereid-array-multiple-where-conditions-laravel-4 – Laerte May 07 '18 at 21:02
2

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;
}
David Barker
  • 14,484
  • 3
  • 48
  • 77
  • 1. The `lists('title')` call returns an array, you can't run `toArray()` on that. 2. When you do `lists('title', 'id')`, you get an associative array of id => title elements. No need to populate the results array manually. Just did a quick tinker check and it works great in L5.1 at least. That said, the behaviour was different in L4, but the question is tagged L5. – Joel Hinz Feb 03 '16 at 14:08