This is the third blog post of Laravel relationship Model tutorial series. In this tutorial, we are going to learn how to implement Many to Many relationship within our Laravel application

Prerequisites

  • Laravel
  • To Continue with this tutorial, you should have installed Laravel in your pc. If you are still not installed Laravel in your machine you can configure it from here.

    Setting up the Project

    First you need to create a new laravel project by running below command in your terminal
    1
    composer create-project laravel/many-to-many-example

    Then navigate to your project directory by using below command in your terminal

    1
    cd many-to-many-example

    Many to Many Relationship will use belongsToMany() relation.

    Create Migration

    Now we have to create migration of "users", "roles" and "role_user" tables.
  • Users table migration
  • 1
    2
    3
    4
    5
    6
    7
    8
    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
  • 1
    2
    3
    4
    5
    Schema::create('roles', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
    });
  • Role_user table migration
  • 1
    2
    3
    4
    5
    6
    7
    8
    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');
    });

    Create Models

    Now we need to create User, Role and UserRole table model. we will also use "belongsToMany()" for relationship of both model.
  • User Model:
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    <?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:
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <?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 Model:
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class UserRole extends Model
    {

    }

    Retrieve Records

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

    Create Records

    1
    2
    3
    $user = User::find(2);	
    $roleIds = [1, 2];
    $user->roles()->attach($roleIds);
    1
    2
    3
    $user = User::find(3);	
    $roleIds = [1, 2];
    $user->roles()->sync($roleIds);
    1
    2
    3
    $role = Role::find(1);	
    $userIds = [10, 11];
    $role->users()->attach($userIds)
    1
    2
    3
    4

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

    In this tutorial, we learn how to implement Many to Many relationship within Laravel. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail.