Laravel - Getting Started - Writing Global Scopes
Writing a global scope is simple. First, define a class that implements the Illuminate\Database\Eloquent\Scope
interface. Laravel does not have a conventional location that you should place scope classes, so you are free to place this class in any directory that you wish.
The Scope
interface requires you to implement one method: apply
. The apply
method may add where
constraints or other types of clauses to the query as needed:
where('created_at', '<', now()->subYears(2000));
}
}
If your global scope is adding columns to the select clause of the query, you should use theaddSelect
method instead ofselect
. This will prevent the unintentional replacement of the query's existing select clause.