How to delete all records of a belongsToMany

Asked

Viewed 784 times

1

In the Laravel, when we have a relationship many for many, we have a method called attach and detach

The attach adds entry into a relationship n:n, and the detach remove them.

In both cases, these operations are performed when an array is passed as parameter

Thus:

class Action extends Eloquent{

   public function roles()
   {
      return $this->belongsToMany('Role', 'roles_actions');
   }
}


class Role extends Eloquent{

    public function actions()
    {
        return $this->belongsToMany('Action', 'roles_actions');
    }
}

So when I want to delete entries from that relationship, I do:

$role = Role::find(1);

$role->actions()->detach([1, 2, 3])
// DELETE FROM roles_actions WHERE action_id IN (1, 2, 3) AND role_id = 1

I would like to know how to delete all entries from this relationship table (without having to specify one by one to do this)

1 answer

1


To delete all relationships, just run the method detach() with no parameter:

$role = Role::find(1);

$role->actions()->detach();
  • 1

    Thanks, @gmsantos. Gave right here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.