Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Collections

Reference1
Reference2
Reference3
Reference4

  1. Creating Collections
  2. Extending Collections
  3. Available Methods

Question

convert-array-to-collection-in-laravel
how to convert array to collection in laravel
*Method1 *
Image description
Image description
Image description
Image description
Image description
Image description

Image description

Image description

Difference between Arrays and Collection
Image description
Image description
Image description

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]);
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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);
    });
});
Enter fullscreen mode Exit fullscreen mode
$collection = collect(['first', 'second']);

$translated = $collection->toLocale('es');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)