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) {
            $table->increments('id');
            $table->bigInteger('fb_id');
            $table->string('name');
            $table->string('email');
            $table->timestamps();
        });

Schema::create('questions', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->string('question');
            $table->timestamps();
        });

Schema::create('participant_answers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('participant_id')->unsigned();
            $table->foreign('participant_id')
                ->references('id')->on('participants');
            $table->integer('question_id')->unsigned();
            $table->foreign('question_id')
                ->references('id')->on('questions');
            $table->string('answer');
            $table->timestamps();
});        

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')
            ->withTimestamps();
    }
}

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

$participant->answers;

Any doubt you can contact me, love to help.