How to Use Query Scope in Laravel Eloquent
Laravel

How to Use Query Scope in Laravel Eloquent

Hello, Today I am sharing with you about query scope in laravel eloquent. Sometimes, we need today's records, yesterday's records, monthly or yearly records, get active records, calculate age, etc. Sometimes, we need to use the same logic again and again in the controller or blade. If we create a query scope, then there is no need to write logic every time.

We can create query scope in laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9. Let's see with an example:

In this tutorial, I would show you with active() scope and it retrieves only active results from the database.

Example 1:

 

<?php
  
namespace App\Model;
  
use Illuminate\Database\Eloquent\Model;
  
class Category extends Model
{
      
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id', 'name', 'slug', 'icon', 'status'
    ];
    /**
     * Scope a query to only include popular users.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }
}

Use Scope Query:

use active() scope to get only active categories

Category::query()->active()->get();

Dynamic Scope In Model:

You can also use dynamic scope and use it anywhere where you want. Let's see how to create dynamic scope

<?php
  
namespace App\Model;
  
use Illuminate\Database\Eloquent\Model;
  
class Product extends Model
{
      
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];
    /**
     * Scope a query to only include popular users.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeProduct($query,$type)
    {
        // type=> food, cake, sweets 
        return $query->where('type', $type);
    }
}

Let's see how to product() scope in the controller

Product::query()->product('food')->get();

//Get another product type

Product::query()->product('sweets')->get();

 

I hope it will help you to make scope query in laravel using eloquent.

Get The latest Coding solutions.

Subscribe to the Email Newsletter