Ad

How To Use WherePivot Method In A Scope?

- 1 answer

I have two models with a pivot.

Domain
{
    public function projects()
    {
        return $this->belongsToMany('Project')->withPivot('is_live');
    }
}

Project
{
    public function domains()
    {
        return $this->belongsToMany('Domain')->withPivot('is_live');
    }
}

Then I try to create the scope "Domains which have Projects and is_live = true" like that Laravel Scope by pivot data values

public function scopeHasLiveProjects($query)
{
    $pivotTable = $this->projects()->getTable();
    return $query->whereHas('projects', function ($q) use ($pivotTable) {
            $q->where($pivotTable . '.is_live', true);
    });
}

But how I can use eloquent method wherePivot('is_live', '=', true) in the scope? Is it possible?!

Ad

Answer

public function scopeHasLiveProjects($query)
{
    return $query->whereHas('projects', function ($q) {
            $q->where('is_live', true);
    });
}

should do the needed

Ad
source: stackoverflow.com
Ad