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.
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:
In a nutshell, instead of defining a many-to-many relationship between
Restaurant, we create a new model on its own with the properties we need (
Review ) which is then linked to the other two (
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.