AppDividend
Latest Code Tutorials

Laravel Many To Many Relationship Example

Laravel 5.6 Eloquent Many To Many Relationship Example

2 725

Get real time updates directly on you device, subscribe now.

In this tutorial, we will see Laravel Many To Many Relationship Example. Many-to-many relations are slightly more complicated than hasOne and hasMany relationships.  Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany. 

In our example, we will define the two models.

  1. Category
  2. Product

In our example, Multiple Categories have Multiple Products, and an inverse relationship will be Multiple Products belongs to Multiple Categories.

So, what we can do is that, when we go to the particular Category, we need to display all the Products.

Same, when we see the particular Product, then we do need to display all the Categories that belongs to that specific Product.

Let us take a Laravel Many To Many Relationship Example and start working on that.

Laravel Many To Many Relationship Example

We start this example, by installing the Laravel 5.6 project.

Step 1: Install Laravel 5.6.

I am using Laravel Valet so that I will create a new project using the following command.

laravel new relationships

Now, if you are not using Laravel Valet then, install using the following command.

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

Go into the project.

cd relationships

Open the project in your editor.

code .

First thing, set up the database.

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.

Now, 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();
        });
    }

Also, write the following schema inside 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();
        });
    }

Now, go to the terminal and create the tables using the following command.

php artisan migrate

Step 3: Define random categories manually.

In this example, we are just focusing on, how many to many relationships works, how we can assign the values and create a relationship with one to another table. So, we create three categories manually inside the database table.

Laravel Many To Many Relationship

 

So, we have manually defined three categories.

Step 4: Define Pivot table.

We have already defined two table schemas 1) Category 2) Product.

Now, we need to define the third table, which is Pivot table. 

The Pivot table is the relationship between two tables.

So Pivot table have these columns.

  1. id
  2. category_id
  3. product_id

Now, we are creating Many to Many relationships, that is why any number of products have any number of categories. To create a migration file, type the following command.

php artisan make:migration create_category_product_table --create=category_product

Now, 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();
        });
    }

Now, migrate using the following command.

php artisan migrate

Step 5: Define the relationships.

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

// Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Also, same for the products. Multiple Products belongs To Multiple Categories. So inside 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);
    }
}

So, 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.

In a real-time scenario, we create a form and then through POST request, we insert the Product data into the table. However, in this example, we will not define any form, we directly store the data into the database, because our goal is how we can use many to many relationships to the complex scenario.

Now, define a route that saves the product into the database as well as assigns the product to the category using many to many relationships. Now, we have four(4) categories. So, we create a product and assign the two categories to one product.

First, create a ProductController using the following command.

php artisan make:controller ProductController

Next step, define the route to store the product.

Related Posts
1 of 33

Now, I am using GET request for the saving 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 the models in this ProductController.php file.

Also, Now, what we are going to do is that we will create one Product that belongs To Many Categories.

In this example tutorial, we are going to create a Product called God of War.

Now, 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 so that it will create two rows in the category_product table.

Now, 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';
    }
}

Explanation.

First, we have created the product and save in the products table.

Now, it is time, to assign the categories to the newly created product.

Since we just need an ID of categories, so right now, I have coded manually, but in real-time, you have those ids in the form request.

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

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

You can see the “Success.”

Now, go to the database and see the products table.

Many To Many Relationship in Laravel

 

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

If we have done all correctly, then 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, and that is and 4.

Laravel 5.6 Many To Many Relationships

 

Yayy!!, we have successfully attached the two categories to one product.

Next step is to display the Product Information and in that, display all the Categories inside that Product.

Step 7: Display the 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'));
}

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

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

Write the following code inside 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, and that is the magic of Eloquent Relationships in the Laravel.

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

As you can see that, we have only one product created so that we can see only One product detail.

 

Laravel attach() function

So, this is how you can add the 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 it.

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 hover to the MySQL database and check the category_product table.

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

 

Laravel detach() Function

So, this is how you can maintain the many to many relationships in Laravel.

Finally, our Laravel Many To Many Relationship example tutorial is over.

2 Comments
  1. Alex says

    Hi,

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

    1. Krunal says

      Yes, sorry, I have updated the code.

Leave A Reply

Your email address will not be published.