Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of Models from a laravel collection

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?

like image 326
MightyPork Avatar asked Aug 04 '16 18:08

MightyPork


1 Answers

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();
like image 189
patricus Avatar answered Oct 03 '22 21:10

patricus