If you are a beginner in Laravel you might find the concept of Pivot table a bit complex. But as is the case with any other feature, working with a pivot table in Laravel is a breeze.

In this tutorial, I will go over in details of when and why will you need it, how you can generate a pivot table and how to attach and detach pivot data.

Alright, First things First. Let's understand the scenario where you would need a pivot table.

Consider the following scenarios.

You are working on an e-commerce project where a product can belong to a category. This is straight-forward.

A product belongsTo category and a category hasMany product.

What If a product can belong to multiple categories?

Consider the following scenarios as well,

  • A post can be attached to multiple tags.
  • A user can belong to multiple Roles.

pivot table is used to build a relationship between two tables where there is a Many to Many relationship.

Defining Many to Many Relationship in Laravel

Consider an example of blog application. Where a Post can be attached to multiple tags. We will need many to many relationship here since A post can have multiple tags and also a tag can be associated to multiple post.

To store the relationship we will require an additional table.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function tags(){
        return $this->belongsToMany('App\Category');
    }
}

Defining this relationship assumes that the table name is post_tag and the key. You can override the table name to a different name by passing it as a second argument.

Once the relationship is defined, you may access the post's tags using the roles dynamic property:


$post = App\Post::find(1);

foreach ($post->tags as $tag) {
    //
}

Generating Pivot Table

You can generate the additional pivot table by running the migration command in your terminal / command-line

php artisan make:migration create_product_tag_table

By convention, Laravel expects the related model names in alphabetical order (you can break with this convention if you prefer).

Migration File

In your table, you should have the primary key column of both the tables that you are generating a pivot table for. In this case, we will have the migration file with the following columns.

public function up()
{
     Schema::create('post_tag',function(Blueprint$table)
     {
          $table->bigIncrements('id');
          $table->bigIncrements('post_id');
          $table->bigIncrements('tag_id');
          $table->timestamps();
     });
}

Insert / Remove Data to Pivot Table

Once you have the relationship defined and the migration file ready, you should now be able to use your pivot table to store the data.

Laraevl provides additional helper methods to make working with a pivot table more convenient.

To insert the data into pivot table you can use the attach method on the relationship

$post->tags()->attach($tag_id);

You can also pass in an array to the attach method to insert multiple entries at once.

$post->tags()->attach([1, 2, 3]);

Similarly to remove the association you can use the detach method.

$post->tags()->detach($tag_id);

There is also an additional helper method sync, which can accept the array. sync will remove the attach the keys that are passed into the array and will detach whatever is not there in the array. So, after sync is complete, only the IDs in the given array will exist in the pivot table:

$post->tags()->sync([1, 2, 3]);

That's all about pivot table in Laravel

Comments