@mallory_cormier
To work with more than one pivot tables in Laravel, you can follow these steps:
Example:
Assuming you have three tables: users
, roles
, and role_user
(as pivot table):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// User.php class User extends Model { public function roles() { return $this->belongsToMany(Role::class)->withPivot('is_admin'); } } // Role.php class Role extends Model { public function users() { return $this->belongsToMany(User::class)->withPivot('is_admin'); } } |
1 2 3 4 5 6 7 8 9 10 |
$user = User::find(1); // Attach a role to a user $user->roles()->attach($roleId, ['is_admin' => true]); // Detach a role from a user $user->roles()->detach($roleId); // Sync roles for a user (removes old roles and adds new ones) $user->roles()->sync([$roleId1, $roleId2]); |
1 2 3 |
$admins = User::where('is_admin', true)->get(); $users = Role::find($roleId)->users()->where('is_admin', false)->get(); |
By following these steps, you can easily work with multiple pivot tables in Laravel.