06.10.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 294<br />

first() {#collection-method}<br />

The first method returns the first element in the collection that passes a given truth test:<br />

1 collect([1, 2, 3, 4])->first(function ($value, $key) {<br />

2 return $value > 2;<br />

3 });<br />

4<br />

5 // 3<br />

You may also call the first method with no arguments to get the first element in the collection. If<br />

the collection is empty, null is returned:<br />

1 collect([1, 2, 3, 4])->first();<br />

2<br />

3 // 1<br />

flatMap() {#collection-method}<br />

The flatMap method iterates through the collection and passes each value to the given callback. The<br />

callback is free to modify the item and return it, thus forming a new collection of modified items.<br />

Then, the array is flattened by a level:<br />

1 $collection = collect([<br />

2 ['name' => 'Sally'],<br />

3 ['school' => 'Arkansas'],<br />

4 ['age' => 28]<br />

5 ]);<br />

6<br />

7 $flattened = $collection->flatMap(function ($values) {<br />

8 return array_map('strtoupper', $values);<br />

9 });<br />

10<br />

11 $flattened->all();<br />

12<br />

13 // ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];

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

Saved successfully!

Ooh no, something went wrong!