Make Reusable queries using Query Scope in Laravel

In Laravel with the use of scope in Model, you can save time of writing the same script in multiple places in your project.

For example, selecting records based on their status – active/inactive/suspended.

The query scope methods are prefixed by scope.

In this tutorial, I show how you can create a reusable query using Query scope in Laravel 9.

Make Reusable queries using Query Scope in Laravel


Contents

  1. Scope method without argument
  2. Scope method with argument
  3. Calling scope method in Controller
  4. Conclusion

1. Scope method without argument

  • Open a Model where you want to create scope method.
  • Add scope prefix with the method name.
  • Create scopeActive() method that takes a single parameter $query. Here, $query is the Eloquent builder instance.
  • Return records where status field value is equal to 1.

Completed Code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
     use HasFactory;
     protected $fillable = [
          'emp_name','email','city','status'
     ];

     public function scopeActive($query){
         return $query->where('status',1)->get();
     }

}

2. Scope method with argument

Create a scopeActiveByCity() that takes 2 parameters –

  • $query – Eloquent builder instance.
  • $args – Dynamic value.

Using this method fetch all active records from a specific city and return it.

Completed Code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
     use HasFactory;
     protected $fillable = [
         'emp_name','email','city','status'
     ];

     public function scopeActiveByCity($query,$args){
         return $query->where('status',1)
              ->where('city',$args)
              ->get();
     }
}

3. Calling scope method in Controller

While calling a scope method remove scope prefix from the method name.

Calling scopeActive() method –

$active_records = Employees::active();

Calling scopeActiveByCity() method –

$activebycity_records = Employees::activeByCity('bhopal');

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employees;

class EmployeesController extends Controller
{
     public function index(){

         // All active records
         $active_records = Employees::active(); 
 
         // All active records from bhopal city
         $activebycity_records = Employees::activeByCity('bhopal');

         dd($activebycity_records);

     }
}

4. Conclusion

You can replace your repetitive query with scope. It saves time and is easier to manage.

When you made any changes to the query in the scope method then it affects all the place where it is been used.

If you found this tutorial helpful then don't forget to share.

Leave a Comment