Understanding Query
Scopes in Eloquent
Laravel Meetup Okinawa #3
nunulk
Slide 2
Slide 2 text
Who am I?
$I->am(‘nunulk’)
->workAs(‘a freelance programmer’)
->tackleComplexityOfSoftware()
->with([
‘Domain-Driven Design’,
‘Laravel’
]);
Slide 3
Slide 3 text
Global Scopes
“Global scopes allow you to add constraints to
all queries for a given model.”
Eloquent: Getting Started - Laravel
Slide 4
Slide 4 text
Global Scopes
“Global scopes allow you to add constraints to
all queries for a given model.”
Eloquent: Getting Started - Laravel
Slide 5
Slide 5 text
Global Scope
class Task extends Model
{
}
// retrieving todo list
$todos = Task::whereNull(‘done_at’)->get();
Slide 6
Slide 6 text
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();
Slide 7
Slide 7 text
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();
Slide 8
Slide 8 text
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();
Slide 9
Slide 9 text
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
Slide 10
Slide 10 text
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
Slide 11
Slide 11 text
Local Scopes
class Task extends Model
{
}
// retrieving expired todo list
Task::->where(‘deadline’, ‘<’, Carbon::now())->get();
Slide 12
Slide 12 text
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();