#belongsToMany() relation with Soft Deletes?

3 messages · Page 1 of 1 (latest)

grizzled prawn
#

Hey guys,

I'm using a belongsToMany() relation where the pivot table contain a deleted_at column.
But in the result, I get all the entities including the deleted ones.

return $this->belongsToMany(View::class, 'view_users'); // return me the entities with a deleted_at != NULL in 'view_users'

Do you know if there is a solution for that ?

#

ChatGPT say to use ->withPivot('deleted_at', null), but it's supposed to be the default behavior, no ?

red agate
#

You can't use regular soft deletes with pivot. The easiest is probably to just define separate relationships for active and inactive relations, like

public function activeViews(): BelongsToMany
{
    return $this->belongsToMany(View::class)->wherePivotNull('deleted_at');
}

public function inactiveViews(): BelongsToMany
{
    return $this->belongsToMany(View::class)->wherePivotNotNull('deleted_at');
}

Pro-tip: If you name the pivot table according to the convention, it should be called user_view (alphabetical order, in singular form). Then you don't have to specify the table name in the relation.