Query Scopes - convenient way to isolate often-used conditions

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!

No comments yet…

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by