Skip to content

Mohcin Bounouara

Thoughts about software engineering and life

Pivot table in Laravel

When you work on an app that requires a many-to-many relationship between tables, you often need a pivot table in your database to manage the associations between records. Let’s consider a simple database schema as an example:

  • Table: posts (Columns: id, body)
  • Table: categories (Columns: id, name)

Suppose you need to link each post with one or multiple categories. In this scenario, you require a third table to centralize and track which categories are associated with each post. This intermediary table is commonly referred to as a “pivot table” in relational databases. It helps aggregate and present data in a more structured way.

In Laravel’s Eloquent ORM, a pivot table is used to establish a many-to-many relationship between two models, such as the Post model and the Category model. Here’s how we describe the relationship in our models:

Post Model:

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'body',
    ];

    public function categories()
    {
        return $this->belongsToMany(Tag::class);
    }
}

Category Model:

class Category extends Model
{
    use HasFactory;

    protected $fillable = ['name'];

    public function posts()
    {
        return $this->belongsToMany(Post::class);
    }
}

Pivot Table Model:

class PostCategory extends Model
{
    protected $table = 'post_category';
    use HasFactory;
}

Once you have the appropriate migration files for posts, categories, and the pivot table (post_category), you can start using the pivot table to manage many-to-many relationships.

For example, when you add a new post with associated categories, you can use the categories() method on the Post model to retrieve a BelongsToMany relationship collection of categories.

In your Blade template, you can loop through the posts and display their categories:

@foreach ($posts as $post)
    <article>
        <div class="entry-text mb-5">
            {!! $post->body !!}
        </div>
        @foreach ($post->categories as $category)
            <span>{{ $category->name }}</span>
        @endforeach
    </article>
@endforeach

By following this approach, you can efficiently manage many-to-many relationships using pivot tables in Laravel. 

Hope the article is clean and helpful.