What Is Many to Many Eloquent Relationship In Laravel Framework

admin_img Posted By Bajarangi soft , Posted On 07-09-2020

Many-to-many relations are slightly more complicated than hasOne and hasMany relationships.Many to many relationship is a little bit complicated than one to one and one to many relationships.Many To Many Relationship relate a record in on the table to one or many records in another table, and vice versa. Unlike One to Many and One to One, in this relationship type, the key is the join and created as pivot table. A pivot table allows the relationship id from one model to be related to many other models and vice-versa

What Is Many to Many Eloquent Relationship In Laravel Framework

Many to Many Eloquent Relationship

Lets start.
How to define Many To Many Eloquent Relationship


1.Create laravel project and connect to database in .env file.

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


2.Create Model and Migrate it.
To implement  Many to Many relationship in Laravel, we need models: Categories , Products and Product_Categories.

Now we need to create Categories ,Products and  Product_Categories models in fresh project so for that run below commands in comand prompt.

php artisan make:model Categories -m

php artisan make:model Products -m

php artisan make:model  Product_Categories -m


3.After Created Models we need to Implement code in Model and migration files as below

Migration files
2020_09_07_064922_create_categories_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreatecategoriesTable extends Migration
{
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->text('name');
            $table->text('discription');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    public function down()
    {
        Schema::drop('categories');
    }
}


2020_09_07_043900_create_products_table.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductTable extends Migration
{
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('name');
            $table->integer('price');
            $table->text('description');
            $table->text('image');
            $table->timestamps(); 
            $table->softDeletes();
        });
    }

    public function down()
    {
        Schema::dropIfExists('products');
    }
}


Product_Categories is pivot table.

Connecting Categories and  Product  tables using a link table called Pivot Table. The pivot table is a relationship table which will hold the category_id and product_id in it.

2020_09_07_064944_create_product__categories_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductCategoriesTable extends Migration
{
 
    public function up()
    {
        Schema::create('product__categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('category_id')->unsigned();
            $table->integer('product_id')->unsigned();

            $table->foreign('category_id')->references('id')->on('categories');
            $table->foreign('product_id')->references('id')->on('products');
            $table->timestamps();
        });
    }

 
    public function down()
    {
        Schema::dropIfExists('product__categories');
    }
}


Models
Categories.php

<?php

namespace App\Models;

use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class categories extends Model
{
    use SoftDeletes;
    public $table = 'categories';
   
    protected $dates = ['deleted_at'];


    public $fillable = [
        'name',
        'discription'
    ];

    protected $casts = [
        'name' => 'string',
        'discription' => 'string'
    ];

  
}


Products.php
<?php

namespace App\Models;

use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class products extends Model
{
    use SoftDeletes;

    public $fillable = [
        'name',
        'price',
        'description',
        'image',
      
    ];

    public $table = 'products';

    protected $dates = ['deleted_at'];

    protected $casts = [
        'id' => 'integer',
        'name' => 'string',
        'price' => 'string',
        'description' => 'string',
        'image' => 'string',
    ];

    public static $rules = [
        'name' => 'required',
        'price' => 'required'
    ];
}

 

4.Creating a Many To Many Relationship in Categories and Products Models.

Open model files and implement code as below
Defining Many To Many Relationship in Products.php

public function categories()
{
    return $this->belongsToMany('App\Models\categories');
}

Defining Many To Many Relationship in Categories.php
public function products()
{
    return $this->belongsToMany('App\Product');
}
 

5.Implement code in Create many to many relationship 

$categories = ['Fruits', 'Vegetables'];

foreach($categories as $category)
{
    categories::create([
        'name'  =>  $category,
    ]);
}
$product = products::create([
    'name'  =>  'Apple',
    'price' =>  199.99,
]);

$categories = category::find([2,3]); // 'Fruits', 'Vegetables'
$product->categories()->attach($categories);

6.Implement code to fetch many to many relationship data
$category = categories::find(1);
$category->products; // will return all products for the category id 1

print_r($category);
$product = products::find(1);
$product->categories; // will return all categories for the product id 1
print_r($product);

7.Implement code to delete many to many relationship
$category = categories::find(2);
$product = products::find(1);

$product->categories()->detach($category);


8.Create shop_cart controller to access data from many to many relationship
php artisan make:controller Shop_cartController

Open shop_cart controller and implement as below

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\categories ;
use App\products ;

class Shop_cartController extends Controller
{
    public function manytomany()
    {
        $category = categories::find(1);
        $category->products; // will return all products for the category id 1

        print_r($category);
        $product = products::find(1);
        $product->categories; // will return all categories for the product id 1
        print_r($product);  
    }
}
 

Implement code to create Route in  Web.php file

Route::get('manytomany', 'Shop_cartController @manytomany')->name('manytomany');

Related Post