11.08.2017 Views

codebright

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Eloquent Collections<br />

I love collections. I have far too many of them. As a kid I used to collect eggcups and transformer<br />

toys. As an adult I collect video games and manga comics. Nerdy collections are the best.<br />

Laravel has its own collections too. It has a collection of wonderful fans, eager to help eachother<br />

and develop the community. It has a collection of amazing developers contributing to it. It has a<br />

collection of stories about where the name came from, most of them false. It also has Eloquent<br />

Collections.<br />

The Collection Class<br />

Eloquent collections are an extension of Laravel’s Collection class with some handy methods for<br />

dealing with query results. The Collection class itself, is merely a wrapper for an array of objects,<br />

but has a bunch of other interesting methods to help you pluck items out of the array.<br />

In Laravel three, an array of model instances was returned from any query method that is used to<br />

provide multiple results. However, in Laravel four you will instead receive a Collection of model<br />

instances. Don’t worry, you can still iterate through a collection of results with the variety of loops<br />

that PHP offers because it inherits some properties of an array, but because the collection is a class,<br />

and not native type, there are also methods available on the object.<br />

Let’s take a look at the available methods of the Collection class. For our sample data we will use<br />

the albums table from the previous chapter, and assume that the collection is the result of a call to<br />

Album::all(), like this.<br />

1

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

Saved successfully!

Ooh no, something went wrong!