WherePivot and WherePivotIn – additional filters for many-to-many relationships

Recently I’ve found a small detail in Laravel documentation which I want to share with you. Apparently, it’s possible to filter pivot tables additionally, if needed. Let me show you how.

Imagine a simple situation: we have tables products, categories and a pivot table category_product with this relationship:

And there are a few products entered – one with each different category: category_id = 1 and category_id = 2:


And we want to show product list in the table – here’s how it looks (code and table generated by our QuickAdmin):

products list

As you can see, column Category lists all possible categories, code looks like this:

And now, here’s a magic trick: what if for some reason we want to show only categories with
category_product.id = 1?

There are additional methods for that: wherePivot() or wherePivotIn().
Then relationship looks like this:

Or like this:

And then what happens in our table? It shows only Category 1, even if there are entries with Category 2:

pivot table wherepivotin

Of course, you can also filter entries bigger/smaller than X, with ->wherePivot(‘id’, ‘>’, 1) or something like that.

As I said – small detail, but might be useful to avoid tons of code for filtering!

More on many-to-many relationships – in official documentation.

Liked the article? We not only write, we also create useful tools!
Have you seen our tool to generate Laravel adminpanel online?
You don't need any packages to do that!

2 thoughts on “WherePivot and WherePivotIn – additional filters for many-to-many relationships

Leave a Reply

Your email address will not be published. Required fields are marked *