Search code examples
phplaravelmodelrelationshipwhere-clause

Laravel - How to detach with condition?


I want to detach values from a model based on a condition. I want to detach all people from the organization whose type is 3, which are workers. But when I try to do so, it detaches all people, not taking into account the where condition.

here are my relationships:

Class: Organization

public function people()
{
    return $this->belongsToMany(People::class, 'organization_people')
}

public function workers()
{
    return $this->people()->where('type', 3); //returns all workers
}

public function detachWorkers()
{
    $this->workers()->detach(); // this detaches all people, I want it to detach only workers
}

Solution

  • You need to do this:

    public function people()
    {
        return $this->belongsToMany(People::class, 'organization_people')
    }
    
    public function workers()
    {
        return $this->people()->where('type', 3);
    }
    
    public function detachWorkers()
    {
        $this->people()->detach($this->workers); 
    }
    
    

    IIUC Laravel will not append that where contstraint onto the detach. Howerver, it will append any contstraints that you place on the pivot table directly, such as $this->people()->wherePivot('type', 3); assuming that you have a type column on the pivot table.