Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ToxifiedM's avatar

How to detach a role of the user with belongsToMany relationship

I have implemented a relationship between users and roles using role_user pivot. I am successfully able to detach the role, while deleting a user, from the database. So basically, I detach the role first then I delete the user. How can I do the same thing using the object cloning method.

Detaching User's Role Then Deleting The User

public function deleteSelected()
    {
        $user = User::whereKey($this->selected)->first();
        $user->roles()->detach();
        $user->delete();
    }

To successfully delete a user, I need to detach the role first, then only the user will be deleted. How can I implement the same above function, but by using the below code format.

public function deleteSelected()
    {
        (clone $this->usersQuery)
            ->unless($this->selectAll, fn($query) => $query->whereKey($this->selected))
            ->delete();
    }
0 likes
1 reply
ToxifiedM's avatar
ToxifiedM
OP
Best Answer
Level 1
public function deleteSelected()
    {
        (clone $this->usersQuery)
            ->unless($this->selectAll, fn($query) => $query->whereKey($this->selected)->first())
            ->roles()->detach();

        (clone $this->usersQuery)    
            ->unless($this->selectAll, fn($query) => $query->whereKey($this->selected)->first())
            ->delete();
        
        $this->showDeleteModal = false;
    } 

Please or to participate in this conversation.