DEV Community

mostafalaravel
mostafalaravel

Posted on

7 2

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more