Skip to main content
Tutorial Free

Query Scopes - convenient way to isolate often-used conditions

September 24, 2015
1 min read
One of less-known but useful Eloquent functions are scopes - basically, you can define conditions to be re-used in various other places in code. Here's an overview. Real-life example: let's say we have list of products and sometimes we have to filter expensive products, and sometimes less valuable. So instead of doing ->where('price', '>', $x) every time, we will define that as a scope. All we need is a new method in Product model - with prefix "scope":
class Product extends Model
{

// ...

    public function scopeExpensive($query)
    {
        return $query->where('price', '>', 100);
    }

    public function scopeCheap($query)
    {
        return $query->where('price', '<', 100);
    }
And then wherever we need to filter expensive or cheap products, we use it like this:
$expensive_products = Product::expensive()->get();
$cheap_products = Product::cheap()->get();
Such approach has two benefits - not only less-repeating code, but also separating one condition into a separate method, and if we need to change that condition (for example, "expensive" would mean 200 instead of 100), we change only that method instead of all the code everywhere in the app.

Scopes with variables

Getting back to the example of price 100 changing into 200, we can make it a variable. For that we just add one more parameter to Model method and then pass the value when calling the method:
public function scopeCheap($query, $price)
{
  return $query->where('price', '<', $price);
}
And then pass the price as parameter:
$cheap_products = Product::cheap(200)->get();
So this is a quick overview of query scopes functionality. Hope it's useful!

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.