How to use Query builder with eloquent in laravel 8

Building Query:

Eloquent models are query builder as well .So we can do everything in eloquent which is possible with query builder.

$house=house::where('id',1)
    ->orderBy('id')
    ->take(1)
    ->get();
dd($house);

Collection:

The Laravel collection class provide us some helpful function to retrieve data Such as get, sum , all, average etc .

$house=house::where('id',1)
           ->get();
dd($house);

Chunk:

IF we have thousand of records we can use chunk method instead of get() or all();

owner::chunk(1,function ($owner){
    foreach ($owner as $ow){
        var_dump($owner);

    }
});

If record is updating while retrieving the data we have to use chunkById instead of chunk method.

owner::chunkById(1,function ($owner){
    foreach ($owner as $ow){
        dd($owner);

    }

},$column='id');

Lazy Method:

It is similar to chunk but instead of providing full set of 200 or more records at once it generates a lazycollecton.

$owner=owner::lazy();
foreach ($owner as $ow)
{
    dd($ow);

}

lazycollecton  use php generator.

https://www.php.net/manual/en/language.generators.overview.php

Curser:

It also use php generator internally. It only executes one database query so , it cannot use relationships.

$owner=owner::cursor();
foreach ($owner as $ow)
{
    dd($ow);
}

Advanced Subquery:

We can add subquery using addSelect method by which we can get information of a single query

$owner=owner::addSelect(['owner_name'=>house::select('id')
    ->where('id','1')
 ])->get();
dd($owner);

 OrderByDesc :

$owner=owner::orderByDesc(house::select('id')
    ->where('id','1')
    ->orderByDesc('id')
)->get();

dd($owner);

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top