How to ReFactor Default Query Scope in Laravel

 Hello artisan,

In this brand new tutorial, I will show you how we can refactor our Laravel default query scope and we can optimize our query using our modifying query scope. We all know how to write Laravel queries using query scope.

But in this example, we will see the process of refactoring Laravel query scope and how to write our modifying query scope. You know that using Laravel query scope, we can avoid the pain of repeated database queries with Laravel query scopes.

Let's see how we can do that. In the default query scope, what we do? 

App\Models\Task.php

public function scopeActive(Builder $query) : void
{
    $query->where('status', 1);
}

 

Then we call this method in our controller like:

Route::get('/', function () {
    return @App\Models\Task::Active()->get();
});

 

But we would like to modify this query scope. How we can do that. Just follow the below steps to refactor laravel query scope.

App\Query\TaskQueryBuilder.php

namespace App\Query;

use Illuminate\Database\Eloquent\Builder;

class TaskQueryBuilder extends Builder
{
    public function getActiveTaskList() : self
    {
        return $this->where('status', 1);
    }
}

 

Now update your Task model like:

App\Models\Task.php

namespace App\Models;

use App\Query\TaskQueryBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Task extends Model
{
    use HasFactory;

    public function newEloquentBuilder($query) : TaskQueryBuilder
    {
        return new TaskQueryBuilder($query);
    }

}

 

And finally, call it from controller like

Route::get('/', function () {
    return @App\Models\Task::getActiveTaskList()->get();
});

 

Read also: Laravel 8.x Eloquent Model Query Scope Example

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js