How to create many-to-many relationship in laravel?

by cali_green , in category: PHP Frameworks , 7 months ago

How to create many-to-many relationship in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 7 months ago

@cali_green 

To create a many-to-many relationship in Laravel, you need to follow these steps:

  1. Create the migration files for the two tables you want to create the relationship between. For example, if you have a "users" table and a "roles" table, you would need to create migration files for both tables.
  2. Define the relationships in the models of the two tables. For example, in the User model, you would define a belongsToMany relationship with the Role model, and in the Role model, you would define a belongsToMany relationship with the User model.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// User.php
public function roles()
{
    return $this->belongsToMany(Role::class);
}

// Role.php
public function users()
{
    return $this->belongsToMany(User::class);
}


  1. Create a pivot table that will store the relationships between the two tables. This table should have columns for the foreign keys of both tables. For example, if you have a "role_user" pivot table, it would have columns for the "role_id" and "user_id".
  2. Use the withPivot() method to specify any additional columns you want to retrieve from the pivot table when accessing the relationship.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// User.php
public function roles()
{
    return $this->belongsToMany(Role::class)->withPivot('created_at');
}

// Role.php
public function users()
{
    return $this->belongsToMany(User::class)->withPivot('created_at');
}


  1. To attach or detach relationships between the two tables, you can use the attach() and detach() methods on the relationship.
1
2
3
4
$user = User::find(1);
$user->roles()->attach($roleId);

$user->roles()->detach($roleId);


By following these steps, you can create a many-to-many relationship between two tables in Laravel.