Home / Blog /

Scopes to custom QueryBuilders

3 years ago

Scopes to custom QueryBuilders

As you might be aware, reusing certain query scopes is fairly straightforward using Local scopes. But it feels a bit dirty to bother our models with this logic, especially since every function has to be prefixed with scope. Fortunately, there is an easier way to define these reusable scopes using separate QueryBuilder classes.

👀 467 views

Creating a custom QueryBuilder class is very simple. Create a PHP class wherever you like. Personally, in a smaller projects, I tend to define my QueryBuilders in the App\QueryBuilders directory. The class looks as follows:

<?php

namespace App\QueryBuilders;

use App\Models\YourModel;
use Illuminate\Database\Eloquent\Builder;

class YourModelNameQueryBuilder extends Builder
{
    public function example(): Builder
    {
        return $this->where('type', 'example');
    }
}

The function defined in this class should return in an instance of the Illuminate\Database\Eloquent\Builder class. This makes it possible to chain multiple query constraints. You can use the above example as follows:

YourModel::example()->get();

Should return all instances of YourModel that are of type example.