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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With