'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 1:[1]
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();
Solution 2:[2]
I had a similar or the same problem and faced it twice during last 2 years.
I figured out that the relation used soft deletion and it made this problem.
My relation belongsToMany
used Pivot
class.
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Eloquent\SoftDeletes;
class EntityUser extends Pivot
{
use SoftDeletes; // it makes the problem
// some code
}
The table had column deleted_at
. But the problem was made SoftDeletes
class.
When I run $user->entities()->detach($entity)
it returned 1
that means one record was touched or removed, but the table and real results had no changes.
I removed SoftDeletes
and it had worked. I also removed that column from the table.
Solution
- Remove
SoftDeletes
from the pivot class. Laravel doesn't have official support of it. https://github.com/laravel/nova-issues/issues/2750 - Remove
deleted_at
from the pivot table. https://laravel.com/docs/9.x/migrations#available-command-aliases
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | brice |
Solution 2 | Oleg Dmitrochenko |