Many-To-Many (Pivot Table) with Extra Columns in Laravel

Image for post
Image for post

Hey everybody, welcome to my first Medium article.

Here is a helpful tip for those who want to model a many-to-many relationship with extra columns or fields in a Laravel app with Eloquent.

Please note that this is not a step-by-step guide through the process of setting up a Laravel app from scratch; instead, I am just sharing a certain way of doing things — implementing a design paradigm if you like.

What is an entity table?

This is the typical scenario that arises when you realise that you want to add new properties to a relational join table so far having nothing but foreign keys.

In such case, the join table becomes a so-called entity table.


So, let’s say we are writing a web app where users can rate and review restaurants in their area.

Models involved:

As said before, with this paradigm the reviews table is not a mere join table (pivot table) but an entity on its own containing properties too: points and comment.

In a nutshell, instead of defining a many-to-many relationship between User and Restaurant, we create a new model on its own with the properties we need (Review ) which is then linked to the other two (User and Restaurant) through a couple of one-to-many relationships, respectively.

Using our entity model in a controller

Finally, this is a minimalist example showing how the Review model can be used.

And that’s all for now! Thanks very much for reading and I hope this will help.

Written by

Hi there! How are you today? I blog about technology, the Internet, SEO, programming tips, PHP and more.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store