Search code examples
laravelpivotpivot-tablelaravel-8

Laravel 8 wherePivot() with dynamic parameter


I need to filter some models according many to many relation so I would like to use wherePivot() filter. But it seems it is impossible to send dynamic param to belongsToMany relation. Is it possible or not? I have something like this:

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function customer($customer_id)
{
    return $this->belongsToMany(Customer::class, 'event_customers', 'event_id', 'customer_id')
        ->wherePivot('customer_id', $customer_id);
}

How can I call it if it is possible?


Solution

  • One way to achieve this would be to have a scoped Query inside your model where you can receive a parameter and then using that scope you can retrieve this many-to-many relation data.

    So, it would be something like this:

    Model:

    public function scopeFilter($customer_id) {
       return $this->customer()->wherePivot('customer_id', $customer_id);
    }
    

    Controller:

    public function index() {
       //.. Rest of Logic
       Model::filter($customerId);
       //.. Rest of Logic
    }
    

    This may need some modifications according to your need. But, I hope it helps.