Reference1
Reference2
Reference3
Reference4
- Creating Collections
- Extending Collections
- Available Methods
Question
convert-array-to-collection-in-laravel
how to convert array to collection in laravel
*Method1 *
Difference between Arrays and Collection
Creating Collections
As mentioned above, the collect helper returns a new Illuminate\Support\Collection instance for the given array. So, creating a collection is as simple as:
$collection = collect([1, 2, 3]);
The results of Eloquent queries are always returned as Collection instances.
Extending Collections
Collections are "macroable", which allows you to add additional methods to the Collection class at run time. The Illuminate\Support\Collection class' macro method accepts a closure that will be executed when your macro is called. The macro closure may access the collection's other methods via $this, just as if it were a real method of the collection class. For example, the following code adds a toUpper method to the Collection class:
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
Collection::macro('toUpper', function () {
return $this->map(function ($value) {
return Str::upper($value);
});
});
$collection = collect(['first', 'second']);
$upper = $collection->toUpper();
// ['FIRST', 'SECOND']
Typically, you should declare collection macros in the boot method of a service provider.
Macro Arguments
If necessary, you may define macros that accept additional arguments:
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Lang;
Collection::macro('toLocale', function ($locale) {
return $this->map(function ($value) use ($locale) {
return Lang::get($value, [], $locale);
});
});
$collection = collect(['first', 'second']);
$translated = $collection->toLocale('es');
Top comments (0)