Laravel 9 Many to Many Eloquent Relationship Example Tutorial

Laravel many to many eloquent relationship; Through this tutorial, i am going to show you what is many to many relationship and how to use many to many relationship in laravel apps.

Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of a many-to-many relationship is a user that has many roles and those roles are also shared by other users in the application. For example, a user may be assigned the role of “Author” and “Editor”; however, those roles may also be assigned to other users as well. So, a user has many roles and a role has many users.

Laravel 9 Many to Many Eloquent Relationship Tutorial

  • Create Migrations
  • Create Models
  • Retrieve Records
  • Create Records

Create Migrations

Create “users”, “roles” and “role_user” table using migration. And then add foreign key with users and roles table.

First of create users table migration; so use the following code:

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

    $table->increments('id');

    $table->string('name');

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

    $table->string('password');

    $table->rememberToken();

    $table->timestamps();

});

Then create roles table migration; so use the following code:

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

    $table->increments('id');

    $table->string('name');

    $table->timestamps();

});

Then create role_user table migration; so use the following code:

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

To create User, Role and UserRole table model. And use “belongsToMany()” for relationship of both model.

Create User Model; and add the following code into it:

<?php
 
namespace App\Models;
 
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');
    }
}

Create Role Model; and add the following code into it:

<?php
 
namespace App\Models;
 
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');
    }
}

Then create UserRole Model; and add the following code into it:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class UserRole extends Model
{
     
}

Retrieve Records

Use the following queries to get or fetch records from database using relationship in laravel apps:

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

Create Records

Use the following queries to create records from database using relationship in laravel apps:

$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);
$role = Role::find(2);	 $userIds = [10, 11];$role->users()->sync($userIds);

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *