Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

assignRole is not working?? #491

Open
Jpac14 opened this issue Jan 20, 2025 · 1 comment
Open

assignRole is not working?? #491

Jpac14 opened this issue Jan 20, 2025 · 1 comment
Assignees

Comments

@Jpac14
Copy link

Jpac14 commented Jan 20, 2025

Hi All,

I am using spatie/laravel-permissions with filament shield. But I am trying to use assignRole on the user model but it is not adding it in to the database and not updating and I have no clue why.

I have installed everything correctly I believe and all the roles exist.

              BulkAction::make('assignRoles')
                ->form([
                  Forms\Components\Select::make('roles')
                    ->multiple()
                    ->options(Role::query()->pluck('name', 'name'))
                    ->preload()
                    ->searchable(),
                ])
                ->action(
                    fn (array $data, User $user) => $user->assignRole($data)
                )
                ->modalWidth(MaxWidth::Large),

^^^ here I am trying to use assignRole.

And even in this listener I am trying add the default role when the user registers, but is not working and I have made sure this listener is registered and working with logging but nothing.
Even when I change default to a role that doesn't exist like asd it comes with an error, but when it stays as default it doesn't throw and error but it doesnt add the role to the user.

class AddDefaultRoleToNewUser
{
  /**
   * Handle the event.
   *
   * @param  \Illuminate\Auth\Events\Registered  $event
   * @return void
   */
  public function handle(Registered $event): void
  {
      $user = User::find($event->user->id);
      $user->assignRole('default');
  }
}
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
            AddDefaultRoleToNewUser::class,
        ],

my user model:

namespace App\Models;

use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements FilamentUser, MustVerifyEmail
{
    use HasApiTokens;
    use HasFactory;
    use Notifiable;
    use HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'email_verified_at',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    /**
     * Get the points requests submitted by the user.
     */
    public function requests()
    {
        return $this->hasMany(PointsRequest::class, 'submitted_by');
    }

    public function canAccessPanel(Panel $panel): bool
    {
        return true;
    }
	
}

find the two files attached for my configuration files and also any seeder or migrations you might need:

additionally I am using stancl tenancy, but this shouldn't make a difference to assign role I believe, because filament when adding in through the relations feature they have works perfectly fine.
it also works fine when i do it with tinker.
Please any help would be appreciated on this matter.

@tonypartridge
Copy link
Contributor

              BulkAction::make('assignRoles')
                ->form([
                  Forms\Components\Select::make('roles')
                    ->multiple()
                    ->options(Role::query()->pluck('name', 'name'))
                    ->preload()
                    ->searchable(),
                ])
                ->action(
                    fn (array $data, User $user) => $user->assignRole($data)
                )
                ->modalWidth(MaxWidth::Large),

Wouldn't assign the roles. You need to use

This was my role assigning using teams.

  BulkAction::make('role_assign')
                    ->label('Assign Role')
                    ->icon('heroicon-o-user-plus')
                    ->form([
                        // team select
                        Select::make('team')
                            ->options(function () {
                                return Team::orderBy('name')
                                    ->where('active', 1)
                                    ->pluck('name', 'id');
                            })
                            ->label('Team')
                            ->live()
                            ->required(),
                        Select::make('role_assign')
                            ->visible(fn ($get) => (int) $get('team') > 0)
                            ->options(function ($get) {
                                $query = Role::orderBy('name');
                                $operator = '=';
                                if ($get('team') > 1) {
                                    $operator = '!=';
                                }

                                return $query->where('team_id', $operator, 1)->pluck('name', 'id');
                            })
                            ->multiple()
                            ->required(),
                    ])
                    ->action(function ($records, $data) {
                        foreach ($records as $record) {
                            $current_team_id = $record->current_team_id;
                            setPermissionsTeamId(1);
                            $record->assignRole($data['role_assign']);
                            setPermissionsTeamId($current_team_id);
                        }
                    }),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants