Many-to-many relationships let you connect two types of data where each item can relate to many items of the other type. It helps organize complex connections easily.
0
0
Many-to-many (belongsToMany) in Laravel
Introduction
When a user can have many roles, and each role can belong to many users.
When a student can enroll in many courses, and each course has many students.
When a product can have many tags, and each tag can apply to many products.
Syntax
Laravel
public function roles() {
return $this->belongsToMany(Role::class);
}Use belongsToMany() inside your Eloquent model to define the many-to-many link.
Laravel expects a pivot table named alphabetically by the two related tables, e.g., role_user.
Examples
This example shows a User model linked to Role model with a many-to-many relationship.
Laravel
class User extends Model { public function roles() { return $this->belongsToMany(Role::class); } }
The Role model also defines the inverse many-to-many relationship back to User.
Laravel
class Role extends Model { public function users() { return $this->belongsToMany(User::class); } }
Attach a role to a user by adding a record in the pivot table.
Laravel
return $user->roles()->attach($roleId);Remove a role from a user by deleting the pivot table record.
Laravel
return $user->roles()->detach($roleId);Sample Program
This example shows how a User model defines a many-to-many relationship to Role. We simulate a user with two roles and print their names.
Laravel
<?php use Illuminate\Database\Eloquent\Model; class User extends Model { public function roles() { return $this->belongsToMany(Role::class); } } class Role extends Model { public function users() { return $this->belongsToMany(User::class); } } // Simulate fetching a user and listing their roles $user = new User(); // Assume roles() returns a collection of Role objects with 'name' property $user->setRelation('roles', \Illuminate\Support\Collection::make([ (object)["name" => "Admin"], (object)["name" => "Editor"] ])); foreach ($user->roles as $role) { echo $role->name . "\n"; }
OutputSuccess
Important Notes
The pivot table must have the two foreign keys named by default as singular model names with _id, e.g., user_id and role_id.
You can customize the pivot table name and keys by passing arguments to belongsToMany().
Use attach(), detach(), and sync() methods to manage pivot table records easily.
Summary
Many-to-many relationships connect two models where each can have many of the other.
Use belongsToMany() in both models to define the link.
Laravel uses a pivot table to store the connections between the two models.