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

Transcript

  1. 3.

    Global Scopes “Global scopes allow you to add constraints to

    all queries for a given model.” Eloquent: Getting Started - Laravel
  2. 4.

    Global Scopes “Global scopes allow you to add constraints to

    all queries for a given model.” Eloquent: Getting Started - Laravel
  3. 5.

    Global Scope class Task extends Model
 {
 } // retrieving

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

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

  5. 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();
  6. 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();
  7. 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
  8. 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
  9. 11.

    Local Scopes class Task extends Model
 {
 } // retrieving

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