29.07.2016 Views

laravel-5

Create successful ePaper yourself

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

Eloquent: Getting Started 433<br />

query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException<br />

will be thrown:<br />

.<br />

1 $model = App\Flight::findOrFail(1);<br />

2<br />

3 $model = App\Flight::where('legs', '>', 100)->firstOrFail();<br />

If the exception is not caught, a 404 HTTP response is automatically sent back to the user, so it is<br />

not necessary to write explicit checks to return 404 responses when using these methods:<br />

.<br />

1 Route::get('/api/flights/{id}', function ($id) {<br />

2 return App\Flight::findOrFail($id);<br />

3 });<br />

Retrieving Aggregates<br />

Of course, you may also use the query builder aggregate functions such as count, sum, max, and<br />

the other aggregate functions provided by the query builder. These methods return the appropriate<br />

scalar value instead of a full model instance:<br />

.<br />

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

2<br />

3 $max = App\Flight::where('active', 1)->max('price');<br />

Inserting & Updating Models<br />

Basic Inserts<br />

To create a new record in the database, simply create a new model instance, set attributes on the<br />

model, then call the save method:<br />

.

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

Saved successfully!

Ooh no, something went wrong!