LaravelLaravel21 min read

Many-to-Many Relationships: Pivot Tables the Right Way

Model many-to-many data with pivot tables, attach/detach, and keep queries clean.

Olivia James
November 13, 2025
3.5k144

Many-to-many relationships are common:
- users belong to many roles
- posts have many tags
- products belong to many categories

    This requires a pivot table.
    
    ## Example: posts and tags
    
    Tables:
    - posts
    - tags
    - post_tag (pivot)
    
    ## Relationship definitions
    
    Post model:
    
    ```php
    public function tags() {
      return $this->belongsToMany(Tag::class);
    }
    ```
    
    Tag model:
    
    ```php
    public function posts() {
      return $this->belongsToMany(Post::class);
    }
    ```
    
    ## Attach tags
    
    ```php
    $post->tags()->attach([1, 2, 3]);
    ```
    
    ## Sync tags
    
    ```php
    $post->tags()->sync([2, 4]);
    ```
    
    ## Graph: relationship structure
    
    ```mermaid
    flowchart LR
      A[posts] --> C[post_tag pivot]
      B[tags] --> C
    ```
    
    In the next tutorial, we will optimize many-to-many queries using eager loading and pivot data.
#Laravel#Database#Eloquent#Advanced