Many to Many Eloquent Relationship in laravel?

users table migration:

File name : index.php

Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->timestamps();

});

roles table migration:

File name : index.php

Schema::create('roles', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->timestamps();

});

role_user table migration:

File name : index.php

Schema::create('role_user', function (Blueprint $table) {

$table->integer('user_id')->unsigned();

$table->integer('role_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users')

->onDelete('cascade');

$table->foreign('role_id')->references('id')->on('roles')

->onDelete('cascade');

});

User Model

File name : index.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
use Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];

/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];

/**
* The roles that belong to the user.
*/
public function roles()
{
return $this->belongsToMany(Role::class, 'role_user');
}
}

Role Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany(User::class, 'role_user');
}
}

UserRole

File name : index.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserRole extends Model
{

}

Retrieve Records:

File name : index.php

$user = User::find(1);

dd($user->roles);
$role = Role::find(1);

dd($role->users);

Create Records:

File name : index.php

$user = User::find(2);

$roleIds = [1, 2];
$user->roles()->attach($roleIds);
$user = User::find(3);

$roleIds = [1, 2];
$user->roles()->sync($roleIds);


$role = Role::find(1);

$userIds = [10, 11];
$role->users()->attach($userIds);

File name : index.php

$role = Role::find(2);

$userIds = [10, 11];
$role->users()->sync($userIds);

File name : index.php


Example Many to Many

Many (Multiple Customers) To (Has) Many (Multiple Products)

many to many eloquent relationship with product and customer example. Customers can purchase various products, and products can be purchased by many customers

Here most important thing is, many to many relationship require three database models, two main models (i.e. products and customers in our example) and one intermediate or pivot table (i.e. customer_product) which will store the foreign keys (i.e. customer_id and product_id) pointing to each related pair of records.

Create Product Model And Migration File

File name : index.php

php artisan make:model Product -m

File name : 2019_11_27_231125_create_products_table.php

public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('product_name');
$table->string('product_price');
// You can add more fields if you need
$table->timestamps();
});
}

File name : Product.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'product_name', 'product_price'
];
}

php artisan make:model Customer -m

File name : 2019_11_27_233730_create_customers_table.php

public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('firstname');
$table->string('lastname');
$table->string('email');
// You can add more filds if you need
$table->timestamps();
});
}

Customer.php

File name : Customer.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'firstname', 'lastname', 'email'
];
}

Creating Pivot Table

we need to connect these two tables using a link table called Pivot Table. The pivot table is a relationship table which will hold the customer_id and product_id in it. You can store more information in the pivot table.

Name of the pivot table should consist of singular names of both tables, separated by undescore symbole and these names should be arranged in alphabetical order, so we have to have product_shop, not shop_product.

File name : index.php

php artisan make:migration create_customer_product_table

artisan make:migration:pivot

File name : index.php


php artisan make:migration create_customer_product_table --create --table=customer_product

File name : 2019_11_28_002257_create_customer_product_table.php

public function up()
{
Schema::create('customer_product', function (Blueprint $table) {
// $table->bigIncrements('id'); // -- Not Require
// $table->timestamps(); // -- Not Require
$table->unsignedBigInteger('customer_id');
$table->unsignedBigInteger('product_id');
});
}

File name : Customer.php

class Customer extends Model
{

// OTHER CODE
/**
* The products that belong to the customer.
*/
public function products()
{
return $this->belongsToMany('App\Product');
}
}

File name : index.php

return $this->belongsToMany('App\Product', 'customer_product', 'product_id', 'customer_id');

Add or Remove Many To Many Relationship Data

File name : index.php

$customer = App\Customer::find(1);
$customer->products()->attach([1,2,3]);

File name : index.php

$customer->products()->detach([1,2,3]);

File name : index.php

$customer->products()->sync([1,2,3]);

Retrieve Many To Many Relationship Data

File name : index.php

$customer = App\Customer::find(1);
foreach ($customer->products as $product) {
//
}





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here


Ittutorial