In this blog, we will discuss how to convert a PHP array to a laravel collection. how to convert a multi-dimensional array to a collection object. Here we check the proper way to convert array to collection.
Laravel change simple array to collection
We can change a simple array to collection object by collect() method. pass an array in the collect method and perform all collection operations on this array.
public function index() { $arr = [1,3,5,7,9]; $collection = collect($arr); dd($collection); }
Laravel convert multi dimensional array to collection
You can also convert multi dimension array to collection by collect method and use object method with ever array.
public function index() { $collection = collect([ (object) ['id'=>1, 'name'=>'Anmol', 'country'=>'India'], (object) ['id'=>2, 'name'=>'Krishan', 'country'=>'India'], (object) ['id'=>3, 'name'=>'Alok', 'country'=>'US'] ]); dd($collection); }
Read Also : Laravel nested relationship with eager loading
Laravel push an array to collection
Use laravel push() method use to add an array to collection object.
public function index() { $collection = new Collection(); $collection->push((object)['id'=>1, 'name'=>'Anmol', 'country'=>'India']); dd($collection); }