Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with scope:
class User extends Model {
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
<span class="token cVar">public</span> <span class="token cVar">function</span> <span class="token cMod">scopeWomen</span><span class="token cBase">(</span><span class="token parameter">$query</span><span class="token cBase">)</span>
<span class="token cBase">{</span>
<span class="token cVar">return</span> $query<span class="token cBase">-</span><span class="token cBase">></span><span class="token cMod">whereGender</span><span class="token cBase">(</span><span class="token cString">'W'</span><span class="token cBase">)</span><span class="token cBase">;</span>
<span class="token cBase">}</span>
}
Usage:
$users = User::popular()->women()->orderBy('created_at')->get();
Sometimes you may wish to define a scope that accepts parameters. Dynamic scopes accept query parameters:
class User extends Model {
public function scopeOfType($query, $type)
{
return $query->whereType($type);
}
}
Usage:
$users = User::ofType('member')->get();