Many-to-Many — Laravel

A many-to-many relation links two models where both sides have many partners: one user can hold many roles, and one role is held by many users. The pairs are…

Once a person needs two roles, the plain PHP shortcut is usually a text column roles holding "admin,editor", checked with strpos. That works, until you want to find every editor, or rename one role.

A many-to-many relation solves it cleanly. This relation links two tables where both sides can have many partners in the other table. In the Library app, one person can hold several roles, such as admin and catalogue editor. One role can also be held by several people. Picture the duty book on the staff desk. Every line in that book holds just one pair: "Budi holds admin", "Budi holds editor", "Ani holds librarian". To find Budi's roles, look for the lines with Budi. To find every librarian, look for the librarian lines. In a database, that duty book is called a pivot table, and each of its rows holds one pair of a user and a role.

Why a third table

In the Eloquent Relationships lesson, a loan only had to store a user_id. Here one column isn't enough. A role_id column in the users table can store only one role for each user, and a user_id column in the roles table can store only one person for each role. So the pairs live in a third table:

users roles role_user (pivot)
1 Budi 1 admin user 1, role 1
2 Ani 2 editor user 1, role 2
3 Citra 3 librarian user 2, role 3

Budi holds admin and editor, Ani holds librarian, and Citra is an ordinary member with no role. This is the pivot table's migration:

Schema::create('role_user', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->foreignId('role_id')->constrained()->cascadeOnDelete();
    $table->primary(['user_id', 'role_id']);
});

belongsToMany on both models

The relation is written on both models:

use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class User extends Model
{
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class);
    }
}

class Role extends Model
{
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }
}
select "roles".*, "role_user"."user_id" as "pivot_user_id", "role_user"."role_id" as "pivot_role_id" from "roles" inner join "role_user" on "roles"."id" = "role_user"."role_id" where "role_user"."user_id" = 1

The result is a Collection holding admin and editor. From the other side, Role::find(3)->users holds Ani. $budi->roles->contains(1) answers true, because role 1 is in that Collection.

attach, detach, sync

To change the pairs, use the relation with parentheses, $budi->roles(). Every row of the table below starts from the same state: Budi holds roles 1 and 2. The SQL is exactly what Laravel 13 sends to SQLite:

Code SQL sent Budi's roles afterwards
attach(3) insert into "role_user" ("role_id", "user_id") values (3, 1) 1, 2, 3
detach(2) delete from "role_user" where "role_user"."user_id" = 1 and "role_user"."role_id" in (2) 1
sync([1, 3]) select * from "role_user" where "role_user"."user_id" = 1, then delete ... in (2), then insert ... values (3, 1) 1, 3
detach() delete from "role_user" where "role_user"."user_id" = 1 none

📌 Extra columns on the pivot

A pivot may have columns of its own, such as when a role was given. Add $table->timestamps() to the pivot's migration, then ->withTimestamps() on the relation: return $this->belongsToMany(Role::class)->withTimestamps();. Other columns are listed with ->withPivot('assigned_by') so they are fetched too. Such a column is filled with attach(3, ['assigned_by' => 2]), then read through $role->pivot->assigned_by ($role is one role from $budi->roles). When one table must pair with many kinds of model (tags for books and for articles), see the Polymorphic Relations lesson. Using roles for permissions is covered in the Role-based Access Control lesson.

The two relations you fill in the exercise

In the exercise, the starter code already has class User with a method roles() and class Role with a method users(), both empty. Fill roles() with return $this->belongsToMany(Role::class); and users() with return $this->belongsToMany(User::class);. The simulator loads both classes and prints Class defined: User and Class defined: Role. The relations are graded from the code: it must contain belongsToMany(.

⚠️ Pivots that can't be found, pairs added twice

TL;DR: A many-to-many relation links two models where both sides have many partners: one user can hold many roles, and one role is held by many users. The pairs are stored in a third table, the pivot table. The pivot table's name is both model names in the singular, in alphabetical order: role_user. It holds user_id and role_id, which together are the primary key, so the same pair can't be recorded twice. On both models write return $this->belongsToMany(...): roles() on User, users() on Role. Read without parentheses: $budi->roles (the user Budi's roles) sends one query with a JOIN to the pivot. Change with parentheses ($budi->roles()): attach(3) adds a pivot row for role 3, detach(2) deletes the row for role 2, detach() deletes all of Budi's roles. sync([1, 3]) makes Budi's roles exactly that list (deleting what's not in the list, adding what's new), then returns an array with attached, detached, updated. Attaching a pair that already exists is refused by the database. Extra pivot columns use withTimestamps() and withPivot(...).

⚡ A third table for the pairs

Write:

Schema::create('role_user', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->foreignId('role_id')->constrained()->cascadeOnDelete();
    $table->primary(['user_id', 'role_id']);
});

Meaning: In a many-to-many relation, one user can hold many roles, and one role is held by many users. The pairs are stored in a third table, the pivot table. Each pivot row holds one pair, such as "Budi holds admin". primary([...]) makes sure the same pair can't be recorded twice. The pivot table's name is both model names in the singular, in alphabetical order, joined by an underscore: role comes before user, so role_user.

⚡ belongsToMany on both sides

Write:

class User extends Model
{
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class);
    }
}

Meaning: User uses belongsToMany(Role::class) in a roles() method, and Role uses belongsToMany too, in a users() method. Neither side holds a foreign key, because both foreign keys are in the pivot. When $budi holds the user Budi, $budi->roles (no parentheses) reads the Collection of his roles.

In the exercise, fill in roles() and users(), both with return.

⚡ attach, detach, sync

Guess first: sync([...]) makes Budi's roles exactly the list you give it. Budi holds roles 1 and 2. After $budi->roles()->sync([1, 3]), which roles does he hold?

1 and 3. sync deletes what's not in the list (2), adds what's missing (3), and leaves what already matches (1).

Meaning: Pairs are changed through the relation with parentheses, $budi->roles(): attach(3) adds a pivot row for role 3, detach(2) deletes the row for role 2, and sync([...]) makes Budi's roles exactly that list.

What you will learn