I am using Laravel Nova with the Spatie Permissions package (version 5.10.2 on Laravel 10.21.0 / Laravel Nova 4.26.5) and facing an issue where roles are not being attached to a user when I'm using an Eloquent observer. Here's the observer method:

public function saved(User $user): void
{
    if (!$user->roles->count()) {
        $role = Role::where('name', 'Client')->first();
        if($role) {
            $user->assignRole($role);
        }
    }
}

This method is supposed to assign a 'Client' role to a user if they do not already have one, but it's not working within the observer. However, the same code works perfectly when called from a controller. Here's what I've checked so far:

  • It works fine when I try to update the user using Tinker or inside a controller.
  • The saved method is definitely being triggered, confirmed by logs, except for the attach method. I've tried with DB::insert also, but still no records.
  • There are no errors being logged, Laravel debug mode is enabled.
  • I've ensured that the event is actually firing by placing log statements.
  • I've tried clearing the role cache with php artisan permission:cache-reset.
  • My model observers are registered correctly in a service provider's boot method. Despite these checks, no records are being created in the database when the observer tries to attach the role. When I perform this action from within a controller, it functions as expected.

I am also using Laravel Nova, which might be affecting how the observers work, though I'm not sure how or why that would be the case.

I've been trying to troubleshoot this issue for several hours now and would greatly appreciate any insights or suggestions from the community. Thank you!

I want to attach a default role for user that hasn't one using saved event.

0

There are 0 answers