PHP

Learn Many-to-Many Relationships in Laravel Easily

Updated

laravel many to many

A many-to-many relationship is two belongsToMany declarations and one pivot table. Laravel will find the pivot table without configuration if it is named after the two models in singular snake_case, in alphabetical order. That last clause is where most setups go wrong. Asked what it expects, Laravel says:

Post         belongsToMany(Tag::class     ) -> table post_tag            fk=post_id      related=tag_id
Tag          belongsToMany(Post::class    ) -> table post_tag            fk=tag_id       related=post_id
User         belongsToMany(Role::class    ) -> table role_user           fk=user_id      related=role_id
BlogPost     belongsToMany(Category::class) -> table blog_post_category  fk=blog_post_id related=category_id

Naming the pivot table: role_user, not user_role

If the migration creates a table called user_role but the model declares belongsToMany(Role::class) with no table name, the first query fails with “no such table: role_user”. As the third line above shows, Laravel looks for role_user, because “role” sorts before “user”. Either name the table role_user, or pass the name explicitly:

return $this->belongsToMany(Role::class, 'user_role');

The migration worth writing

Schema::create('post_tag', function (Blueprint $table) {
    $table->id();
    $table->foreignId('post_id')->constrained()->cascadeOnDelete();
    $table->foreignId('tag_id')->constrained()->cascadeOnDelete();
    $table->string('added_by')->nullable();   // an extra pivot column
    $table->timestamps();
    $table->unique(['post_id', 'tag_id']);    // stops duplicate pairs
});

The unique index is what makes attach() safe to call twice. Without it you get a second identical row and no error. With it:

$post->tags()->attach(4);   // already attached
rejected: SQLSTATE[23000]: Integrity constraint violation: 19
          UNIQUE constraint failed: post_tag.post_id, post_tag.tag_id
rows for post 2: 3

Pivot rows are plain table rows, so a parent using the SoftDeletes trait leaves them behind untouched, even with the cascadeOnDelete() foreign keys above (why that happens), and asserting relationship state in tests is its own subject.

withPivot and withTimestamps

Extra pivot columns are not loaded unless you ask. withTimestamps() additionally makes Laravel write created_at/updated_at on attach:

public function tags()
{
    return $this->belongsToMany(Tag::class)
        ->withPivot('added_by')
        ->withTimestamps();
}

$post->tags()->attach([1, 2], ['added_by' => 'ada']);
-- post_tag after attach --
post_id=1 tag_id=1 added_by='ada' created_at='2026-08-11 16:44:51'
post_id=1 tag_id=2 added_by='ada' created_at='2026-08-11 16:44:51'
post_id=2 tag_id=2 added_by=NULL created_at='2026-08-11 16:44:51'

-- reading them back --
php:     pivot->added_by='ada' pivot->created_at=2026-08-11 16:44:51
laravel: pivot->added_by='ada' pivot->created_at=2026-08-11 16:44:51

Drop withPivot('added_by') and $tag->pivot->added_by is simply null: the column is still in the table, it just is not selected. Random posts and tags come from factories and Faker, but the pairs between them are still written with attach() or sync().

sync() removes what you leave out

This is the trap. attach adds, detach removes, and sync makes the relationship exactly the list you pass, deleting every pivot row you did not mention. It reports what it did:

post 2 before: laravel, sql
sync([4]) returned: {"attached":[4],"detached":[2,3],"updated":[]}
post 2 after:  ops

Two tags were silently removed. If your controller does $post->tags()->sync($request->input('tags', [])) and the form posts no checkboxes at all, sync([]) detaches everything. When you mean “add these, keep the rest”, the method is syncWithoutDetaching():

after syncWithoutDetaching([2,3]): laravel, sql, ops

toggle() flips membership, and updateExistingPivot($id, [...]) changes pivot columns without touching membership. All exist on BelongsToMany in 13.25.0, along with saveMany() and createMany(). The pivot-table guesses, the withPivot and sync() results, the duplicate-row rejection and the 4-versus-2 query counts on this page are asserted by laravel-many-to-many-relationships.sh in a freshly installed Laravel project, which needs php, composer and network access to run.

The N+1, counted rather than asserted

Three posts, one loop, query log on:

without with('tags'): 4 queries
   select * from "posts"
   select "tags".*, ... where "post_tag"."post_id" = ?
   select "tags".*, ... where "post_tag"."post_id" = ?
   select "tags".*, ... where "post_tag"."post_id" = ?

with    with('tags'): 2 queries
   select * from "posts"
   select "tags".*, "post_tag"."post_id" as "pivot_post_id", "post_tag"."tag_id" as "pivot_tag_id",
          "post_tag"."added_by" as "pivot_added_by", ...
     from "tags" inner join "post_tag" on "tags"."id" = "post_tag"."tag_id"
    where "post_tag"."post_id" in (1, 2, 3)

1 + N becomes 2, and it stays 2 at any number of posts. Look at the second query: eager loading is a whereIn over the parent IDs, and the pivot columns arrive aliased as pivot_*, which is how $tag->pivot gets populated. That IN list has a size ceiling of 65535 bindings on MySQL 8.4 (measured in the whereIn page), so eager loading tens of thousands of parents at once is the one case where with() can fail outright. chunk() or lazy() is the answer there.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.