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

noblemfd's avatar

How to add condition to the Roles retrieved by logged user

I am using Spatie RBAC in my Laravel-5.8 application

I have this code in my user controller and view:

UserController

public function create()
{
    $roles = Role::get()->pluck('name', 'name');
    return view('admin.users.create', compact('roles','companies'));
}

view

    <div class="form-group {{ $errors->has('roles') ? 'has-error' : '' }}">
        <label for="roles">{{ trans('global.user.fields.roles') }}*
            <span class="btn btn-info btn-xs select-all">Select all</span>
            <span class="btn btn-info btn-xs deselect-all">Deselect all</span></label>
        <select name="roles[]" id="roles" class="form-control select2" multiple="multiple">
            @foreach($roles as $id => $roles)
                <option value="{{ $id }}" {{ (in_array($id, old('roles', [])) || isset($user) && $user->roles->contains($id)) ? 'selected' : '' }}>
                    {{ $roles }}
                </option>
            @endforeach
        </select>
        @if($errors->has('roles'))
            <p class="help-block">
                {{ $errors->first('roles') }}
            </p>
            @endif
    </div>

If the Role of the logged in user is not "Super Admin", the role select dropdown should retrieve other roles except "Super Admin". But if the logged in user is "Super Admin", it should retrieve all the roles including "Super Admin".

How do I achieve this?

Thanks

0 likes
1 reply

Please or to participate in this conversation.