How to use Query Scope in Laravel Tutorial Example

Larave Eloquent Query Scope Example. In this tutorial, you will learn how to create and use dynamic eloquent model query scopes in laravel 9 apps.

Laravel scope is just a query, make a query and code to short and faster. We can create custom query with relation or anything with scope. In any admin project we need to get data using status base, just like active, pending, draft something else.

Writing where query all time in controller reside we can use local scope in model and call the function where we need.

Laravel Model Query scope tutorial example

Here we use getting final invoices where the status is 2, we can also use this Dynamic Scopes to getting the status 1, 2, 3 how much status you are using.. You can easily use dynamic query scope in laravel application.

Basically we use to getting the final invoices just like the bellow code.

$status = 2;

$finalInvoices =  Invoice::where(['status', $status])->get();

But if we need to same thing any other module also.So i need write again and again this where queries. Here is the best solution for removing the queries, That call Scope. below we create filter scope in invoice model and then call them where we want use query.

class Invoice extends Model
{
    /**
     * Scope a query to only include draft invoices.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeFilterByStatus($query, $status)
    {
        return $query->where(['status', $status]);
    }

}

Laravel know scope as alias. Now i can get final invoices using Invoice::filterByStatus($status)->get();

We can get all types invoices just changing the status parameter in funcation. If you want draft invoice and the status id is 2 then you add $status = 2 and add themm in the function argument.

$status = 2;
$finalInvoices = Invoice::filterByStatus($status)->get();

Well, you learn about How to use Scopes in Laravel Eloquent Tutorial Example. If you need any help please comment us for more follow us on twitter.

1 thought on “How to use Query Scope in Laravel Tutorial Example”

Leave a Comment