Once you have created a Eloquent model and its associated database table, you can start retrieving data from your database. Think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model. For example:
<?php use App\Product; $products = Product::all(); foreach ($products as $product) { echo $product->name; }
The Eloquent all
method will will return all the rows from products
table.
What if we have to apply certain conditions and pull only those product that meets the conditions? Surely Eloquent models serves powerful Query Builder , which have plenty of methods which can be used to add additional constrains to your queries, and then use the get
method to retrieve the result.
Since Eloquent models are query builders, you should review all of the methods available on the query builder. You may use any of these methods in your Eloquent queries.
<?php use App\Product; $products = Product::where('active', 1) ->orderBy('name', 'desc') ->take(10) ->get(); foreach ($products as $product) { echo $product->name; }
If you have any other questions, experience or insights on "Laravel Eloquent Query Retrieving Models" please feel free to leave your thoughts in the comments bellow which might be helpful to someone!
Be the first one to write a response :(
{{ reply.member.name }} - {{ reply.created_at_human_readable }}