Laravel Eloquent Queries for fetching record

Laravel Eloquent Queries for fetching record

Laravel offer one of the most beautiful, simple ActiveRecord implementation for working with your database. Eloquent Models allow you to query for data in your tables, as well as insert new records into the table.

Let’s say that you have a order table.

Let’s create the Eloquent model for order table.

php artisan make:model Order

This command generates the Eloquent model for order the table. let’s find the model file at app/Order.php file and define table name like below.


namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
    protected $table = "order";

Now, we can perform any SQL query using Eloquent model. Like, let’s get the all records from the order table. The Eloquent model query looks like.

$orders = Order::all();

We get all records of the order table using all the method of the Eloquent model.

We can add the where condition using where like

$order = Order::where('status','=','pending')->get();

Using where method we can get the pending orders list like above.

We can get the single record using find and first Eloquent method like. If we need to find record using id then we use find method like

$order = Order::find(5);

We can find the record by Id using find method.

If you want to get single record find by name then we should used first method like.

$order = Order::where('name','=','LED')->first();

Using the first method we can get the first record with the name of “LED”.

Also, We can set the order for records using orderBy method like.

$order = Order::orderBy('id','DESC')->get();

Using orderBy method we can get the order by descending.

If you need to fetch specific columns instead of “*”, We can get using select method like.

$order = Order::select('id','name')->get();

We can get only “id” and “name” column on the result instead of all columns.

Also, We can set the limit for the records using limit the method like.

$order = Order::limit(10)->get();

If you want to set pagination the Laravel Eloquent provide pagination method we can use it like.

$order = Order::where('status','=','active')->paginate(10);

It’s so simple to set pagination using the Laravel Eloquent method.

Also, We can count the number of records using count method like.

$orderCount = Order::where('status','=','active')->count();

The count method returns the number of records found.

If you want to find the max price order you can use max method for fetching max price order like.

$max = Order::where('status','=','active')->max('price');

If you have any query or suggestion for making this article more helpful please write the comment below.