Hello Devs,

In this tutorial, we are going to learn how to create laravel Many to Many eloquent relationship.

Follow this step by step guide given below:




Step 1:

 Create Migration

php artisan make:model User -m

php artisan make:model RoleUser -m

php artisan make:model Role -m


Path:database\migrations\2014_10_12_000000_create_user_table.php

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

class CreateUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user');
    }
}

Path:database\migrations\2014_10_12_000000_create_role_table.php

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

class CreateRoleTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role');
    }
}

Path:database\migrations\2014_10_12_000000_create_role_users_table.php

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

class CreateRoleUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('user_id');
            $table->integer('role_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_users');
    }
}


Run this command:

php artisan migrate



Step 2:


Create Model Relationship app\user.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    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 attributes that should be cast to native types.
     *
     * @var array
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_users');
    }
}

app\role.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
   /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    Protected $fillable=[
        'name'
    ];
    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    public function users()
    {
        return $this->belongsToMany(User::class, 'role_users');
    }
}

app\RoleUser.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class RoleUser extends Model
{   
    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    public $table = 'role_user';
    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    protected $fillable = [
        'user_id','role_id'
    ];
}



Step 3 : 


Insert Records app\Http\Controllers\user.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Role;

class userController extends Controller
{
    public function createRecored()
    {      
       //create recored in user table
       $user = User::find(2);   
       $roleIds = [1, 2];
       $user->roles()->attach($roleIds);

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

       //create recored in role table

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

       $role = Role::find(2);   
       $userIds = [10, 11];
       $role->users()->sync($userIds);
    }
}



Step 4 : 


Retrieve Records app\Http\Controllers\user.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Role;

class userController extends Controller
{
    public function retrieveRecords()
    {   
        //Retrieve recoed in user table
        $user = User::find(1);    
        dd($user->roles);
        
        //Retrieve recoed in role table
        $role = Role::find(1);  
        dd($role->users);
    }
}


I hope this example helps you.