Laravel Eloquent belongsToMany relationship

Posted by Navdeep Singh on June 29, 2016

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:

Schema::create('participants', function (Blueprint $table) {

Schema::create('questions', function (Blueprint $table) {

Schema::create('participant_answers', function (Blueprint $table) {

In Participant Model we make a connection with Question and Participant Answers via belongsToMany like below

class Participant extends Model {
 public function answers()
        return $this->belongsToMany('App\Question', 'participant_answers', 'participant_id', 'question_id')->withPivot('answer')

'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:

$participant->answers()->sync([$question->id => ['answer' => $request_answer] ]);

And to access all answers of a participant is like :


Any doubt you can contact me, love to help.