Convert Array To Collection in Laravel
Edit; I understand this question is getting a lot of hits based on the title so the TLDR for those people is to use the collect()
helper to create a Collection instance. In answer to the questioner's brief:
If you have
$collection = collect([
(object) [
'website' => 'twitter',
'url' => 'twitter.com'
],
(object) [
'website' => 'google',
'url' => 'google.com'
]
]);
You then have your array wrapped in an instance of the Collection class.
That means it does not behave like a typical array (- it will be array-like, but don't treat it like it is one -) until you call all()
or toArray()
on it. To remove any added indices you need to use values()
.
$sorted = $collection->sortBy('website');
$sorted->values()->all();
The expected output:
[
{#769
+"website": "google",
+"url": "google.com",
},
{#762
+"website": "twitter",
+"url": "twitter.com",
},
]
See the docs https://laravel.com/docs/5.1/collections#available-methods
The toArray
method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays.
The all
method returns the underlying array represented by the collection.
In my case I was making an collection to fake a service for test purpose so I use
$collection = new Collection();
foreach($items as $item){
$collection->push((object)['prod_id' => '99',
'desc'=>'xyz',
'price'=>'99',
'discount'=>'7.35',
]);
}