Search code examples
phplaravellaravel-permission

Laravel Print select options accordingly user's permission


Hope you are doing well.

I'm using spatie's permission package to manage my user's role and permissions.

I have 4 roles

  1. Admin
  2. Super Distributor
  3. Distributor
  4. Retailer

in my user creation from i fetched all roles using Spatie\Permission\Models\Role role model... and foreach looped to generate select values but the twist comes here. Admin can create every type of user but super distributor can only create distributor and retailer, distributor can only create retailer. how to i generate options accordingly user roles?

Currently i wrote this code and its not working at all

<select wire:model="role" name="role" class="block mt-1 w-full border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm block mt-1 w-full">
                <option value="" selected>Please select an option</option>
                @forelse ($roles as $role)
                
                    
                @role('admin')
                    @if ($role == 'admin' || $role == 'super distributor' )
                        <option value="{{ $role->name }}">{{ Str::ucfirst($role->name) }}</option> 
                    @endif
                @endrole 
                    
                @empty
                    <option >There is no roles available</option>  
                @endforelse
            </select>

Thanks in advance

Edit: Thanks to @Abdul Rehman For his solution.

I edited little bit and here is the final solution

public function mount()
    {
        $this->roles = $this->getRoles();
    }

    public function getRoles()
    {
        return [
            'admin' => Role::all(),
            'super distributor' => Role::whereIn('name', ['distributor','retailer','user'])->get(),
            'distributor' => Role::whereIn('name', ['retailer'])->get(),
            'retailer' => [],
            'user' => [],
        ][auth()->user()->roles->pluck('name')[0]];
    }

Solution

  • handle this thing from the controller don't get all roles get roles on the base of which user is login.

    like

    if(auth()->user()->hasRole('Admin')){
     Role::all() //write query to fetch all roles
    }
    
    if(auth()->user()->hasRole('Super Distributor')){
     Role::whereIn('id', [distributor_id,retailer_id])->get(); //write query to get only  distributor and retailer role
    }
    

    get the others as like above query.