Laravel Many to Many Eloquent Relationship: Step-by-Step Guide

Laravel Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany. Many to many relationships are slightly more complicated than hasOne and hasMany relationships.

The join (or pivot) table is the key to the many-to-many relationship. The pivot table allows the relationship id from one model to be related to many other models and vice-versa.

Here are the steps to create many-to-many relationships:

Step 1: Install Laravel.

composer create-project laravel/laravel relationship --prefer-dist

Go into the project.

cd relationships

Step 2: Create a model and migration.

We are defining two models for our example.

  1. Category
  2. Product
php artisan make:model Category -m
php artisan make:model Product -m

It will create products and categories, tables, and models.

Inside create_categories_table, define the following schema.

// create_categories_table

/**
 * Run the migrations.
 *
 * @return void
 */
 public function up()
 {
    Schema::create('categories', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title');
      $table->timestamps();
   });
 }

Write the following schema inside the create_products_table.

// create_products_table

 /**
 * Run the migrations.
 *
 * @return void
 */
 public function up()
 {
   Schema::create('products', function (Blueprint $table) {
     $table->increments('id');
     $table->string('name');
     $table->float('price');
     $table->timestamps();
   });
 }

Go to the terminal and create the tables using the following command.

php artisan migrate

Step 3: Define random categories manually.

Laravel Many To Many Relationship

Step 4: Define a Pivot table.

Many-to-many relations require an intermediary table to manage the relationship.

The most straightforward implementation of the intermediary table, known as a pivot table, would consist of just two columns for storing the foreign keys pointing to each related pair of records.

How to create a Pivot table in Laravel

  1. The name of the pivot table should consist of singular names of both tables, separated by underscore symbols, and these names should be arranged in alphabetical order, so we have to have category_product, not product_category.
  2. To create a pivot table, we can create the simple migration with artisan make:migration. For example, we have the command artisan make:migration:pivot.
  3. Pivot table fields: by default, there should be only two fields – the foreign key to each table, in our case, category_id and product_id. You can insert more fields if you need, then you need to add them to the relationship assignment.

The Pivot table has these columns.

  1. id
  2. category_id
  3. product_id
php artisan make:migration create_category_product_table --create=category_product

Define the following schema in the migration file.

// create_category_product_table

/**
 * Run the migrations.
 *
 * @return void
 */
 public function up()
 {
   Schema::create('category_product', function (Blueprint $table) {
     $table->increments('id');
     $table->integer('category_id')->unsigned();
     $table->integer('product_id')->unsigned();
   });
 }

Migrate using the following command.

php artisan migrate

Step 5: Define Many To Many relationships.

Multiple Categories belong to Multiple Products. So inside the Product.php file, we can define the belongsToMany relationship.

// Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
  public function categories()
  {
    return $this->belongsToMany(Category::class);
  }
}

The same is true for the products. Multiple Products belong To Multiple Categories. So inside the Category.php file, we can define the belongsToMany relationship.

// Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Product;

class Category extends Model
{
  public function products()
  {
    return $this->belongsToMany(Product::class);
  }
}

We have defined the relationship between them.

Now, let us create a new product and assign the category to the Product.

Step 6: Create a Product.

First, create a ProductController using the following command.

php artisan make:controller ProductController

The next step, define the route to store the Product.

I am using a GET request to save the data because we have not created the form, so we take every data manually.

// ProductController.php

Route::get('product/create', 'ProductController@create')->name('product.create');

Import both models in this ProductController.php file.

What we are going to do is we will create one Product that belongs To Many Categories.

In this example tutorial, we will create a God of War product.

Now, the God of War belongs to two categories.

  1. Video Games
  2. Playstation

So, when we create a product, we also need to fill the pivot table with the two categories.

So, our product_id will be one, but the category_id will be different, creating two rows in the category_product table.

Write the following code inside ProductController’s create() function.

// ProductController.php

<?php

namespace App\Http\Controllers;
use App\Category;
use App\Product;

use Illuminate\Http\Request;

class ProductController extends Controller
{
  public function create(Request $request)
  {
    $product = new Product;
    $product->name = 'God of War';
    $product->price = 40;

    $product->save();

    $category = Category::find([3, 4]);
    $product->categories()->attach($category);

    return 'Success';
  }
}

The attach() function will assign those category ids to the newly created Product and create two new rows inside the pivot table. Each row has a relationship with its Product and category.

The next step is going to this URL: http://relationships.test/product/create or http://localhost:8000/product/create

You can see the “Success.”

Go to the database and see the products table.

Many To Many Relationship in Laravel

Also, you can check the Pivot Table, a create_product table.

If we have done it all correctly, we can see the two rows inside the table, where product_id is the same 1 for both the rows, but category_id’s are different, which are and 4.

Laravel 5.6 Many To Many Relationships

Yay!!, we have successfully attached the two categories to one Product.

The next step is to display the Product Information and all the Categories inside that Product.

Step 7: Display Product Information.

Define the route that can display all the information.

// web.php

Route::get('product/{product}', 'ProductController@show')->name('product.show');

Now, define the ProductController’s show function.

In this function, I am using Routing Model Binding.

// ProductController.php

public function show(Product $product)
{
   return view('product.show', compact('product'));
}

We pass the product id in the get request, fetch the product details via Route Model Binding directly, and give that product detail to the view.

Create a new folder inside the views folder called products, and inside that, create one file called show.blade.php.

Write the following code inside the show.blade.php file. We display the product name, price, and belongs to categories.

// show.blade.php

<h2>Product Name: </h2>
<p>{{ $product->name }} || ${{ money_format($product->price, 2) }}</p>

<h3>Product Belongs to</h3>

<ul>
  @foreach($product->categories as $category)
    <li>{{ $category->title }}</li>
  @endforeach
</ul>

As we have defined the relationship, we can directly fetch all the categories from the Product model, which is the magic of Eloquent Relationships in Laravel.

Now, go to this URL: http://relationships.test/product/1 or http://localhost:8000/product/1

As you can see, we have only one Product created to see only one product detail.

Laravel attach() function

This is how you can add multiple categories to a product and display multiple categories for a product.

Now, you can create as many products as you want and assign multiple categories to them.

You can also delete the relationship between the tables using the detach() function.

Detach() function

// ProductController.php

public function removeCategory(Product $product)
{
  $category = Category::find(3);

  $product->categories()->detach($category);
 
  return 'Success';
}

Now, define the following route inside a web.php file.

// web.php

Route::get('category/product/{product}', 
  'ProductController@removeCategory')->name('category.product.delete');

Next, type this URL: http://relationships.test/category/product/1 or http://localhost:8000/category/product/1.

Hit enter, and we get success now. Go to the MySQL database and check the category_product table.

You can see that the category_id = 3 row is deleted, and we no longer belong to category_id = 3.

Laravel detach() Function

This is how you can maintain many-to-many relationships in Laravel.

Related Posts

Laravel OneToMany Relationship

14 thoughts on “Laravel Many to Many Eloquent Relationship: Step-by-Step Guide”

  1. Hi,

    I think there are some error in the “Define the relationships” section (the code is the same for both models)

    Reply
  2. Thank you for your post, Krunal! It really contains useful info for me. I have only one question about defining the schema in the create_category_product_table migration file. Do I need to create an ID field there using this line: $table->increments(‘id’);???

    Or may be this will be enough?:

    Schema::create(‘category_product’, function (Blueprint $table) {
    $table->integer(‘category_id’)->unsigned();
    $table->integer(‘product_id’)->unsigned();
    });

    Reply
  3. Thanks a lot, exactly what I was looking for.

    Something you could add (to avoid stupidly losing time like me), is that Eloquent will look for a table model1_model2 in alphabetical order by default(can be overridden).

    In my case I was working with a User and Hotel model and I created a user_hotel table instead of a hotel_user one.

    Reply
  4. i want to add the category in my form by selecting the specific categories how will I modify the public function store code
    $category = Category::find([3, 4]);
    thank you in advance

    Reply
  5. In CreateCategoryProductTable

    $table->integer(‘category_id’)->unsigned();
    $table->integer(‘product_id’)->unsigned();

    after that we add foreign’s cloumns:

    $table->foreign(‘category_id’)
    ->references(‘id’)
    ->on(‘categories’)->onDelete(‘cascade’);

    $table->foreign(‘product_id’)
    ->references(‘id’)
    ->on(‘products’)->onDelete(‘cascade’);

    Reply
  6. Hi, in find(..) you have add the id of your table product, if product register one category “B” then your get your id of “B” , then your have $product->category_id, well I created my table data base with related bettwen tables and added this relations. then are like this -> find($product->category_id)

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.