Recently I’ve found a small detail in Laravel documentation that 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 tags, images, and a pivot table image_tag with this relationship:

class Tag extends Model
    public function image()
        return $this->belongsToMany(Image::class);

And there are a few tags entered – one with each different image: tag_id = 1 and tag_id = 2:

so we have data something like these in  tag_image

image_id | tag_id
1 | 1
1 | 2
2 | 2

And now, here’s a magic trick: what if for some reason we want to show the only images with having `tag id 2` = 2?

There are additional methods for that: wherePivot() or wherePivotIn().
Which will look like this:

public function image($tagId)
      return $this->belongsToMany(Image::class)->wherePivot('tag_id', $tagId​​​​​​​); 
      // like $tagId = 1, will be whatever value we want to use with where

Or like this for whereIn (multiple records):

public function image(array $tagIds)
      return $this->belongsToMany(Image::class)->wherePivotIn('tag_id', $tagIds​​​​​​​); 
      // like $tagIds = [1, 2]


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

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

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

Leave a Comment

Frontend Developers

Useful Pages

Copyright © 2021 Design by BinBytes