pivot

Sometimes you may wish to use custom pivot model when working with many-to-many relationships in Eloquent, in order to add some behaviour on top of the core features.

There are a few things to consider before you start.

First things first: belongsToMany relationship can presented as double hasMany + belongsTo relations.

Imagine we have categories of posts and users who can subscribe for multiple categories:

* I prefer to use Model class name instead of its Eloquent alias.

This additional model can be used if we need to hook on the pivot table events (what cannot be done on the relation itself – read here for a workaround https://stackoverflow.com/a/28934080)

Another use case would be pivot table that links more than just 2 other tables.

However, this model is just like any other and it is not used by Eloquent, when we call belongsToMany relation on the user or category. So next, let’s define that custom pivot model (we can use both, or just one of these, depending on the needs):

Now, in order to let Eloquent grab this pivot model, we also need to override newPivot method on both User and Category:

The if statement is required, so only this particular relation grabs our custom pivot model. Obviously  we don’t want it to work for other m-m relations if it is specific to user-category only.

Basically this is all we have to do, so let’s check it:

 

As you can see all is working as expected. Now, you’re free to add custom behaviour to the pivot model, so it will work best for you.

There is just one more thing to remember – this custom pivot model won’t be used during sync, attach, detach calls – these are simple queries not touching eloquent.

 

Share your thoughts and questions in the comments!

It's only fair to share...Tweet about this on TwitterShare on RedditPin on PinterestShare on FacebookShare on Google+

Related Post

20 Eloquent tricks – more Recently I stumbled upon interesting article by Povilas Korop on laravel-news 20 eloquent tips and tricks. First of all thanks for sharing your knowle...
A story about Laravel Resources Leo is a brilliant developer. He turns every idea into code in no time. He's prepared for any task thrown at him and dives into coding straight away, ...
How to add custom casters in Laravel tinker I made a series about psysh and Laravel's tinker - powerful REPL where you can play with your whole application. ICYMI check it out here: tinker li...
Too much M4g1c will kill you (or at least bite you... So, as you know, I'm a big fan of Laravel, in particular Eloquent is my favourite. The beauty and value of both is a lot of conventions and magic...