skip to Main Content

I am trying to retrieve data using a belongsToMany relationship in Laravel. So I have Student and Course model and they have a many to many relationship, but there are few courses that are compulsory so we don’t want to keep those in pivot table, instead we have a Boolean column called compulsory. Now, I want to retrieve all courses for all users including the ones that are compulsory in belongsToMany relation.
Any suggestions ?

Student
- id
- name
Course
- id
- name
- compulsory
course_student pivot table
- id
- student_id
- course_id

2

Answers


  1. That looks quite simple, just use where in your relationship definition. If that doesnt work, please share how are your relationships defined. If you separate compulsory and noncompulsory courses quite often, I would stucture my relationsips as such:

     class Student extends Model{
    
       public function courses(): BelongsToMany
    {
        return $this->belongsToMany(Course::class);
    }
    
      public function compulsoryCourses(): BelongsToMany
    {
        return $this->courses()->where('compulsory', 1);
    }
    
      public function noncompulsoryCourses(): BelongsToMany
    {
        return $this->courses()->where('compulsory', 0);
    }
    
    Login or Signup to reply.
  2. you can apply where conditions while you are calling any relationship inside with the use of the callback function.

    Student::with['courses' => function ($q) {
       $q->where('compulsory', 1);
    }];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search