Laravel Eloquent belongsToMany relationship explained using real time example of a quiz app.
Participants registered via Facebook API in Participants table and each day have a one question. And Each day participants need to give answer to that question.
So relation like Participants have many Questions with Answers Table. In Laravel belongsToMany relationship is like many-to-many relationship. Here we can say Participants have many Questions with Pivot table Particpant_Answers
The table structure is like below:
In Participant Model we make a connection with Question and Participant Answers via belongsToMany like below
'participant_answers' is pivot table. Btw what is Pivot table? you may doubted.
Pivot table is table that only come into existence to serve a many-to-many relationship. Say here to get all participant answers we need a table which carry both participant_id, question_id and of course answer.
Insert data into pivot table like below:
And to access all answers of a participant is like :
Any doubt you can contact me, love to help.