6
votes

Given a Collection of Eloquent Models, which are Arrayable, how can I get an array of those objects?

If I call ->toArray() on the collection, it gives me a nested associative array, destroying the models.

If I cast it to an array, I get this REALLY odd thing:

array:1 [▼
  "\x00*\x00items" => array:1 [▼
    "temp" => HistorySeries {#374 ▼
      #table: "history_series_hse"
      #primaryKey: "id_hse"
      #connection: "mysql"
      +timestamps: false
      <...snip...>
    }
  ]
]

Then there's this, but I'm not really liking it (it works):

    $reflection = new ReflectionClass($coll);
    $property = $reflection->getProperty('items');
    $property->setAccessible(true);
    $array = $property->getValue($coll);

Or I could extract it using a foreach loop, but that's ugly. Any nice way?

2
Try $collection->all()? - ceejayoz
Did you tried each() method? - Rajender Joshi

2 Answers

9
votes

The Collection is just a wrapper around a standard array. To get that standard array, call the all() method on the Collection.

// Collection of Item models
$itemsCollection = Item::all();

// standard array of Item models
$itemsArray = $itemsCollection->all();
-1
votes

Don't try to cast to array, instead keep you Collection intact and use high order functions like map or each to do what you need to.

Ex:

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});

$multiplied->all();

You don't specify what you actually need to do with the data so this is just a loose example from the docs.

You can't cast to array and keep the model intact, it won't work.