https://dev.to/codeaxion https://res.cloudinary.com/practicaldev/image/fetch/s--BzM5XfMg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mgzt2nvdiwzswyzqa11g.jpg Rather than describing what scope is because there are already many articles and videos explaining “What Scopes are !”.

Let’s take an example suppose we are making a filter which sorts the products by low-to-heigh , heigh-to-low etc…

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(); }

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(); }} 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); } now lets merge this scope into 1 query
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners