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.

Eloquent: Collections<br />

• Introduction<br />

• Available Methods<br />

• Custom Collections<br />

Introduction<br />

All multi-result sets returned by Eloquent are an instance of the Illuminate\Database\Eloquent\Collection<br />

object, including results retrieved via the get method or accessed via a relationship. The Eloquent<br />

collection object extends the Laravel base collection, so it naturally inherits dozens of methods used<br />

to fluently work with the underlying array of Eloquent models.<br />

Of course, all collections also serve as iterators, allowing you to loop over them as if they were<br />

simple PHP arrays:<br />

.<br />

1 $users = App\User::where('active', 1)->get();<br />

2<br />

3 foreach ($users as $user) {<br />

4 echo $user->name;<br />

5 }<br />

However, collections are much more powerful than arrays and expose a variety of map / reduce<br />

operations using an intuitive interface. For example, let’s remove all inactive models and gather the<br />

first name for each remaining user:<br />

.<br />

1 $users = App\User::where('active', 1)->get();<br />

2<br />

3 $names = $users->reject(function ($user) {<br />

4 return $user->active === false;<br />

5 })<br />

6 ->map(function ($user) {<br />

7 return $user->name;<br />

8 });

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

Saved successfully!

Ooh no, something went wrong!