Why don't you use https://github.com/spatie/laravel-permission?
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

$user = User::whereKey($this - > selected)->first(); //get the record
$user - > roles() - > detach();
$user - > delete();
Please or to participate in this conversation.