Scroll to top

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


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


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 .

Author avatar

Imran is a web developer and consultant from India. He is the founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

Post a Comment

Your email address will not be published. Required fields are marked *