Scopes allow you to define prebuilt scopes
(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 the type
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 with scope
then the title-cased version of the scope name. Also as you can see this method is passed a query builder that you can modify before returning and of course needs to return a query builder.
Also, It's possible to define scope
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)