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 208<br />

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

The map 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 />

.<br />

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

2<br />

3 $multiplied = $collection->map(function ($item, $key) {<br />

4 return $item * 2;<br />

5 });<br />

6<br />

7 $multiplied->all();<br />

8<br />

9 // [2, 4, 6, 8, 10]<br />

Note: Like most other collection methods, map returns a new collection instance; it does<br />

not modify the collection it is called on. If you want to transform the original collection,<br />

use the transform method.<br />

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

The merge method merges the given array into the collection. Any string key in the array matching<br />

a string key in the collection will overwrite the value in the collection:<br />

.<br />

1 $collection = collect(['product_id' => 1, 'name' => 'Desk']);<br />

2<br />

3 $merged = $collection->merge(['price' => 100, 'discount' => false]);<br />

4<br />

5 $merged->all();<br />

6<br />

7 // ['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]<br />

If the given array’s keys are numeric, the values will be appended to the end of the collection:<br />

.

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

Saved successfully!

Ooh no, something went wrong!