Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Understanding Query Scopes in Eloquent

73b0a25ed03f649ec63ded82ce4ac7cb?s=47 nunulk
December 19, 2017

Understanding Query Scopes in Eloquent

Laravel Meetup Okinawa #3

73b0a25ed03f649ec63ded82ce4ac7cb?s=128

nunulk

December 19, 2017
Tweet

More Decks by nunulk

Other Decks in Programming

Transcript

  1. Understanding Query Scopes in Eloquent Laravel Meetup Okinawa #3 nunulk

  2. Who am I? $I->am(‘nunulk’) ->workAs(‘a freelance programmer’) ->tackleComplexityOfSoftware()
 ->with([
 ‘Domain-Driven

    Design’,
 ‘Laravel’
 ]);
  3. Global Scopes “Global scopes allow you to add constraints to

    all queries for a given model.” Eloquent: Getting Started - Laravel
  4. Global Scopes “Global scopes allow you to add constraints to

    all queries for a given model.” Eloquent: Getting Started - Laravel
  5. Global Scope class Task extends Model
 {
 } // retrieving

    todo list
 $todos = Task::whereNull(‘done_at’)->get();

  6. Global Scope class Task extends Model
 {
 protected static function

    boot()
 {
 parent::boot(); // applied to all queries
 static::addGlobalScope(‘todo’, new TodoScope());
 }
 } // retrieving todo list
 $todos = Task::all();
 

  7. Global Scope class TodoScope implements Scope
 {
 public function apply(Builder

    $builder)
 {
 // applied to all queries
 $builder->whereNull('done_at');
 }
 } // retrieving todo list
 $todos = Task::all();
  8. Global Scope class TodoScope implements Scope
 {
 public function apply(Builder

    $builder)
 {
 // applied to all queries
 $builder->whereNull('done_at');
 } public function extend(Builder $builder, Model $model) { $builder->macro('done', function (Builder $builder) { return $builder->withoutGlobalScope($this) ->whereNotNull('done_at'); }); }
 } // retrieving done list
 $todos = Task::done()->get();
  9. Local Scopes “Local scopes allow you to define common sets

    of constraints that you may easily re-use throughout your application.” Eloquent: Getting Started - Laravel
  10. Local Scopes “Local scopes allow you to define common sets

    of constraints that you may easily re-use throughout your application.” Eloquent: Getting Started - Laravel
  11. Local Scopes class Task extends Model
 {
 } // retrieving

    expired todo list
 Task::->where(‘deadline’, ‘<’, Carbon::now())->get();
  12. Local Scopes class Task extends Model
 {
 public function scopeExpired(Builder

    $builder, Carbon $date)
 {
 return $builder->where(‘deadline’, ‘<’, $date);
 }
 } // retrieving expired todo list
 Task::expired(Carbon::now())->get();
  13. Query Scopes ˒Global Scopes •Scope interface •apply, extend •macro ˒Local

    Scopes •scope query method