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
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:
you can apply where conditions while you are calling any relationship inside with the use of the callback function.