Query Scopes
Query scopes are amazing it lets you encapsulate your logic inside models without being repetitive . You can attach a subquery to your existing query. If you want to select all products which are visible to the public then you do something like below
Products::where('visible',1)->get();
In future, if you add one more field out_of_stock and want to check that as well in the query then it will be a nightmare for you to change the query in all places so query scope came in existence to help you. Below is our modified version
Products::visible()->get();
In our Products Model
public function scopeVisible($query)
{
// You can also pass in parameters as second argument ($query,$max)
return $query->where('out_of_stock',0)->where('visible', 1);
}
Now if you want to make any changes to visible products you need to only edit our query scope scopeVisible .
No Comments
Leave a comment Cancel