Search code examples
laravelrelationdetach

Laravel detach not working on belongsToMany


I have this model: Company
Which has a relation: $this->belongsToMany('App\CallList', 'call_list_companies', 'company_id', 'call_list_id')

And vice versa: CallList
Relation: $this->belongsToMany('App\Company', 'call_list_companies', 'call_list_id', 'company_id')

I am able to attach a Company to the CallList
But I cannot detach a Company from a CallList

Why is that?

The code I use for detaching the Company:
$company->call_lists()->detach($call_list);

I also tried the other way:
$call_list->companies()->detach($company);

It just returns null when I do it. I checked that the both the company and the call list exists and that there was a relation between the two in the database.

Anyone have a clue what I am doing wrong? I do not get any errors or anything either.

If it's worth mentioning, I am also using a pivot table for the relations.


Solution

  • Filter the relationship query down to just the call list with matching ID and then call detach().

    Try:

    $company->call_lists()->where('id', $call_list->id)->detach();