Using Laravel Scopes on Pivot Model

Viewed 108

It seems the pivot models are not being used during Eloquent query from the Parent Class.

Let's say that I have a Teacher Model and Student Model. In which we have a rule where teacher has many students and students has many teacher.

by default, I needed to return all the students who are active only. So by adding a wherePivot('active', true) I able to get the list of active through only when using $teacher->students()->get()

This is my Teacher Model and my TeachStudent Pivot Model looks like

class Teacher extends Model
{
   public function students()
   {
      return $this->belongsToMany(Student::class)
          ->using(TeacherStudent::class)
          ->wherePivot('active', true)
   }
}



    class TeacherStudent extends Pivot implements Sortable
    {
        use SortableTrait;

        /**
         * The "booting" method of the model.
         *
         * @return void
         */
        public static function boot()
        {
            parent::boot();

            static::addGlobalScope('customScope', function ($query) {
                // THIS WILL NOT WORK
            });
        }

        public function scopeWithInActive()
        {  
            // THIS WILL NOT WORK
        }
    }

Now, I need to list all students who are regardless of active or inactive, so that on my UI, I can toggle the active status.

Is this achievable?

$teacher->students()->withInActive()->get();

0 Answers
Related