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

ToxifiedM's avatar

How to detach role from multiple user from the role_user pivot table

I have a eloquent relationship between roles table and users table using a pivot. I am able to select multiple users and delete them, successfully, but as I have roles assigned to them, and due to foreign id constrains, I am unable to delete them. As my earlier approach I used to show a delete option beside each user and in the controller, inside the delete method, $user->roles()->detach(); and then $user->delete(); It works all fine for the said approach, but as of now my approach is a bit different, I want to select multiple users and do some bulk actions. But I am unable to detach the role, of the single user or from the array of selected users, I get the following error all to undefined method Illuminate\Database\Eloquent\Builder::roles().

My previous approach is the traditional method, and it works perfectly. Whereas my current approach isn't able to perform, the operation, i.e. detaching the role and user relation.

My Previous Approach

  • Livewire/UserController.php
public function delete($id) {
    $user = User::findOrFail($id);

    $user - > Roles() - > detach();
    $user - > delete();
}
  • views/livewire/user-controller.blade.php
<button wire:click="delete({{ $user->id }})">
    Delete
</button>

My Current Approach

  • Livewire/UserController.php
public $selected = [];

public function deleteSelected() {
    $user = User::whereKey($this - > selected);

    $user - > roles() - > detach();
    $user - > delete();
}
  • views/livewire/user-controller.blade.php
<x-dropdown label="Actions">
    <x-dropdown.item wire:click="deleteSelected" type="button">
        <x-icon.trash /><span>Delete</span>
    </x-dropdown.item>
</x-dropdown>

<x-table>
    <x-slot name="head">
        <x-table.heading>
            <x-input.checkbox />
        </x-table.heading>
    </x-slot>

    <x-slot name="body">
        @foreach($users as $key => $user)
        <x-table.row wire:loading.class.delay="opacity-50">
            <x-table.cell wire:key="row-{{ $user->id }}">
                <x-input.checkbox wire:model="selected" value="{{ $user->id }}" />
            </x-table.cell>
        </x-table.row>
        @endforeach
    </x-slot>
</x-table>

What I'm Trying To Do

Role Error

0 likes
14 replies
ToxifiedM's avatar

The question is not about which package to use or not, its about an unknown error, which wasn't present, when I was using the previous approach.

ToxifiedM's avatar

I gave that a try

Schema::create('role_user', function (Blueprint $table) {
      $table->foreignId('role_id')->constrained();
      $table->foreignId('user_id')->constrained()->onDelete('cascade');
});

But still the same error, Call to undefined method Illuminate\Database\Eloquent\Builder::roles()

Tray2's avatar

Somewhere you are using User::roles() and you most likely don't have a roles method in your User model.

ToxifiedM's avatar

Here are my models with belongsToMany relation. The models are the same as it was before, just the difference is public selected = [] and then instead of passing the $id I used $user = User::whereKey($this - > selected); after this the function does not works, I can assign roles to users, but unable to detach the roles while deleting a single or multiple user.

  • User.php
public function roles() {
        return $this->belongsToMany(Role::class);
}
  • Role.php
public function users() {
        return $this->belongsToMany(User::class);
}
Tray2's avatar

What happens if you do this?

$user = User::first();
dd($user->roles);
ToxifiedM's avatar

Here is the output

Illuminate\Database\Eloquent\Collection {#1356 ▼
  #items: array:1 [▼
    0 => App\Models\Role {#1362 ▼
      #connection: "mysql"
      #table: "roles"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:4 [▶]
      #original: array:6 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "pivot" => Illuminate\Database\Eloquent\Relations\Pivot {#1429 ▼
          +incrementing: false
          #guarded: []
          #connection: "mysql"
          #table: "role_user"
          #primaryKey: "id"
          #keyType: "int"
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:2 [▼
            "user_id" => 1
            "role_id" => 1
          ]
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102
$user = User::whereKey($this - > selected)->first(); //get the record

    $user - > roles() - > detach();
    $user - > delete();
1 like
ToxifiedM's avatar

This is what I wanted, I was unable to determine, what the problem was, thanks alot @sinnbeck appreciate it

ToxifiedM's avatar

@sinnbeck I just wanted to ask, as I need to detach the role of multiple users, how can I do that, because first() is only working for a single user, I am unable to perform the action, on multiple users. I am passing an array of id of the selected users, so what can be used instead of first().

Sinnbeck's avatar

Easiest way would be to either do it with 1 manual query, or get all the users that needs "detach" and do the detach in a foreach :)

Please or to participate in this conversation.