Query scopes

The previous section introduced you to the concept of query scopes. This builds on from the query builder that allows you to build conditions on an ad hoc basis. However, what if you need certain conditions to apply to every request? Or a single condition that is actually the combination of multiple WHERE clauses? This is where query scopes come in.

Query scopes allow you to define these conditions once in your model, and then re-use them without having to manually define the clauses that make up that condition. For example, imagine we need to find users above the age of 21 in multiple places in our application. We can express this as a query scope:

class User extends Model {

  public function scopeOver21($query)
  {
 $date = Carbon::now()->subYears(21); ...

Get Laravel 5 Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.