29.07.2016 Views

laravel-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Collections<br />

• Introduction<br />

• Creating Collections<br />

• Available Methods<br />

Introduction<br />

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with<br />

arrays of data. For example, check out the following code. We’ll use the collect helper to create<br />

a new collection instance from the array, run the strtoupper function on each element, and then<br />

remove all empty elements:<br />

.<br />

1 $collection = collect(['taylor', 'abigail', null])->map(function ($name) {<br />

2 return strtoupper($name);<br />

3 })<br />

4 ->reject(function ($name) {<br />

5 return empty($name);<br />

6 });<br />

As you can see, the Collection class allows you to chain its methods to perform fluent mapping<br />

and reducing of the underlying array. In general, every Collection method returns an entirely new<br />

Collection instance.<br />

Creating Collections<br />

As mentioned above, the collect helper returns a new Illuminate\Support\Collection instance<br />

for the given array. So, creating a collection is as simple as:<br />

.<br />

1 $collection = collect([1, 2, 3]);<br />

By default, collections of Eloquent models are always returned as Collection instances; however,<br />

feel free to use the Collection class wherever it is convenient for your application.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!