DEV Community

mostafalaravel
mostafalaravel

Posted on

Laravel local scopes: easy, simple and clear.

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();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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();
    }

Enter fullscreen mode Exit fullscreen mode

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();
    }

Enter fullscreen mode Exit fullscreen mode

Then you can use this like :

$blackTypeCars = Car::blacktype()->get();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)