DEV Community

Rayees Aadil
Rayees Aadil

Posted on

Scopes are way more powerful than you think !

Image description

Rather than describing what scope is because there are already many articles and videos explaining “What Scopes are !” . Instead, I’ll show you
how powerful scope is and how you can save time by using it .

In short, scopes are not just for querying status active or completed etc…
but today i will show you what they can actually do .

Let’s take an example suppose we are making a filter which sorts the products by low-to-heigh , heigh-to-low etc… a basic filter !,
now if we want to apply this logic we will do it like this :

public $sortBy = "";

switch($this->sortBy){

 case 'low-to-heigh':
    Product::orderBy('sale_price', 'asc')->get();
case 'heigh-to-low':
    Product::orderBy('sale_price', 'desc')->get();
case 'featured':
    Product::where('featured',-1)->get();
default:
    Product::all();
}
Enter fullscreen mode Exit fullscreen mode

Assume if we want to add more filter for eg- filter by category so we can add category like this:

switch($this->sortBy){

  case 'low-to-heigh':
      Product::where('category_id',$categoryId)->orderBy('sale_price', 'asc')->get();

  case 'heigh-to-low':
      Product::where('category_id',$categoryId)->orderBy('sale_price', 'desc')->get();

  case 'featured':
      Product::where('category_id',$categoryId)->where('featured',-1)->get();

  default:
      Product::all();
}
Enter fullscreen mode Exit fullscreen mode

Now if you have noticed we added the category query in every condition so that’s against the D.R.Y principles now this is where scopes comes into play and also this can be a 1 liner , yes you heard that right this can be 1 liner lets see…

First of all we will define a scope called SortBy:
and we will add an additional parameter called $sortBy which will be dynamic and we will copy the filter code into scope

public function scopeSortBy($query,$sortBy)
{
    switch($sortBy){

     case 'low-to-heigh':
        $query->orderBy('sale_price', 'asc')->get();
     case 'heigh-to-low':
        $query->orderBy('sale_price', 'desc')->get();
    case 'featured':
        $query->where('featured',-1)->get();
    default:
        Product::all();
    }
}
Enter fullscreen mode Exit fullscreen mode

now lets define another dynamic scope called scopeCategoryFilter and we will add the category query inside the scope

public function scopeCategoryFilter($query,$category)
{
 $query->where('category_id',$category);
}
Enter fullscreen mode Exit fullscreen mode

now lets merge this scope into 1 query

Product::CategoryFilter($category->id)->SortBy($this->sortBy)->get();
Enter fullscreen mode Exit fullscreen mode

As you can see we reduced so many lines of code into 1 liner and now you can use it anywhere wherever you want
and you can also chain as many scopes as you want !

Top comments (0)