How to connect 3 table with a pivot table in laravel?

by elise_daugherty , in category: PHP Frameworks , 14 days ago

How to connect 3 table with a pivot table in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 13 days ago

@elise_daugherty 

To connect 3 tables with a pivot table in Laravel, you can use Laravel's built-in Eloquent ORM relationships. Here's how you can do it:

  1. Define your Eloquent models for each table:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_roles');
    }
}

class Role extends Model
{
    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'role_permissions');
    }
}

class Permission extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_permissions');
    }
}


  1. Define the pivot tables in your migration files:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Schema::create('user_roles', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');
    $table->unsignedBigInteger('role_id');
    $table->timestamps();

    $table->primary(['user_id', 'role_id']);
});

Schema::create('role_permissions', function (Blueprint $table) {
    $table->unsignedBigInteger('role_id');
    $table->unsignedBigInteger('permission_id');
    $table->timestamps();

    $table->primary(['role_id', 'permission_id']);
});


  1. Use the relationships in your controllers or anywhere else in your application:
1
2
3
4
5
6
7
8
9
$user = User::find(1);
$userRoles = $user->roles;

foreach ($userRoles as $role) {
    $permissions = $role->permissions;
    foreach ($permissions as $permission) {
        echo $permission->name;
    }
}


By defining these relationships in your models and setting up the pivot tables, you can easily connect 3 tables using a pivot table in Laravel.