TIP 07 / 100

Eloquent Scopes Inside of Other Relationships.

Did you know that you can use Eloquent scopes inside of defining other relationships?

app/Models/Lesson.php:

php
public function scopePublished($query)
{
     return $query->where('is_published', true);
}

app/Models/Course.php:

php
public function lessons(): HasMany
{
     return $this->hasMany(Lesson::class);
}

public function publishedLessons(): HasMany
{
     return $this->lessons()->published();
}