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

.<br />

19 return view('flight.index', ['flights' => $flights]);<br />

20 }<br />

21 }<br />

Accessing Column Values<br />

If you have an Eloquent model instance, you may access the column values of the model by accessing<br />

the corresponding property. For example, let’s loop through each Flight instance returned by our<br />

query and echo the value of the name column:<br />

.<br />

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

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

3 }<br />

Adding Additional Constraints<br />

The Eloquent all method will return all of the results in the model’s table. Since each Eloquent<br />

model serves as a query builder, you may also add constraints to queries, and then use the get<br />

method to retrieve the results:<br />

.<br />

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

2 ->orderBy('name', 'desc')<br />

3 ->take(10)<br />

4 ->get();<br />

Note: Since Eloquent models are query builders, you should review all of the methods<br />

available on the query builder. You may use any of these methods in your Eloquent queries.<br />

Collections<br />

For Eloquent methods like all and get which retrieve multiple results, an instance of Illuminate\Database\Eloquent\Collection<br />

will be returned. The Collection class provides a variety of<br />

helpful methods for working with your Eloquent results. Of course, you may simply loop over this<br />

collection like an array:

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

Saved successfully!

Ooh no, something went wrong!