How to join two tables with a pivot table using laravel?

Member

by dedrick , in category: PHP Frameworks , 6 months ago

How to join two tables with a pivot table using laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 6 months ago

@dedrick 

To join two tables with a pivot table in Laravel, you can use the belongsToMany relationship in your Eloquent models. Here's how you can achieve this:

  1. Define the relationship in your Eloquent models:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// User model
class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_roles', 'user_id', 'role_id');
    }
}

// Role model
class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class, 'user_roles', 'role_id', 'user_id');
    }
}


  1. Create a migration for the pivot table user_roles:
1
php artisan make:migration create_user_roles_table


In the migration file, define the schema for the pivot table:

1
2
3
4
5
6
7
8
9
Schema::create('user_roles', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');
    $table->unsignedBigInteger('role_id');
    
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
    
    $table->primary(['user_id', 'role_id']);
});


  1. Use the relationship in your code to join the tables:
1
2
3
4
5
$user = User::find(1);

foreach ($user->roles as $role) {
    echo $role->name;
}


This will fetch the roles associated with the user using the pivot table user_roles and display their names.