Laravel Eloquent Triple Pivot Relations

Solving the HasManyTriple problem

Sometimes you find yourself in the situation where you have a table like shop_country_category, which has the following structure:

countries
- id
- name

shop
- id
- name

products
- id
- name

shop_country_product
- id
- country_id
- shop_id
- product_id

In this case a shop has specific products that differ per country. So, for example in the Shop.php Eloquent model use:

    /**
     * The country-specific products that belong to a shop (triple pivot relation)
     */
    public function countryProducts()
    {
        return $this->belongsToMany('App\Product','shop_country_product')
                    ->withPivot('country_id');
    }

In this way you can access that shop_country_category

Or use a plugin

I’ve not tested it, but I heard this package might work with Laravel 5.

Do you have a better solution?

Do not hesitate to share them in the comments.

Leave a Comment

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

en_USEnglish
Scroll to Top