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: Getting Started 432<br />

.<br />

1 foreach ($flights as $flight) {<br />

2 echo $flight->name;<br />

3 }<br />

Chunking Results<br />

If you need to process thousands of Eloquent records, use the chunk command. The chunk method<br />

will retrieve a “chunk” of Eloquent models, feeding them to a given Closure for processing. Using<br />

the chunk method will conserve memory when working with large result sets:<br />

.<br />

1 Flight::chunk(200, function ($flights) {<br />

2 foreach ($flights as $flight) {<br />

3 //<br />

4 }<br />

5 });<br />

The first argument passed to the method is the number of records you wish to receive per “chunk”.<br />

The Closure passed as the second argument will be called for each chunk that is retrieved from the<br />

database.<br />

Retrieving Single Models / Aggregates<br />

Of course, in addition to retrieving all of the records for a given table, you may also retrieve single<br />

records using find and first. Instead of returning a collection of models, these methods return a<br />

single model instance:<br />

.<br />

1 // Retrieve a model by its primary key...<br />

2 $flight = App\Flight::find(1);<br />

3<br />

4 // Retrieve the first model matching the query constraints...<br />

5 $flight = App\Flight::where('active', 1)->first();<br />

Not Found Exceptions<br />

Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in<br />

routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the

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

Saved successfully!

Ooh no, something went wrong!