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

Understanding Query Scopes in Eloquent

nunulk
December 19, 2017

Understanding Query Scopes in Eloquent

Laravel Meetup Okinawa #3

nunulk

December 19, 2017
Tweet

More Decks by nunulk

Other Decks in Programming

Transcript

  1. Global Scopes “Global scopes allow you to add constraints to

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

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

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

  4. 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();
 

  5. 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();
  6. 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();
  7. 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
  8. 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
  9. Local Scopes class Task extends Model
 {
 } // retrieving

    expired todo list
 Task::->where(‘deadline’, ‘<’, Carbon::now())->get();
  10. 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();