Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

mostafalaravel
mostafalaravel

Posted on

     

Laravel local scopes: easy, simple and clear.

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

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

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

Then you can use this like :

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

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

LARAVEL dev
  • Location
    Brussels
  • Work
    Web developer
  • Joined

More frommostafalaravel

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp