Scopes allow you to define prebuiltscopes
(filters) that you can use either every time your query a model with a specific method chain (Local Scope).
Let's take this example:
$newBlackCars = Car::where('type' , 'like' , 'manual')->where('color' , 'like' , 'black')->get();
The request above will return all black cars where thetype
is manual.
But what if we could make it more simple and shorter?
Something like:
$blackManualCars = Car::blackManuals()->get();
Yes we can! Thanks to the local scope :
class Car{ public function scopeBlackManuals($query){ return $query->where('type' , 'like' , 'manual')->where('color' , 'like' , 'black')->get(); }
To define a local scope, we add a method to the Eloquent class that begins withscope
then the title-cased version of the scope name. Also as you can see this method is passed a query builderthat you can modify before returning and of course needs to return a query builder.
Also, It's possible to definescope
that accept parameters:
class Car{ public function scopeBlackType($query, $type){ return $query->where('type' , 'like' , $type)->where('color' , 'like' , 'black')->get(); }
Then you can use this like :
$blackTypeCars = Car::blacktype()->get();
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse