Laravel-permission: show user roles on edit

Created on 17 Feb 2018  路  5Comments  路  Source: spatie/laravel-permission

Hi,

I try to get user assigned roles on user edit page but i can't.

Here is my blade code:

<label>Roles</label><br>
<select data-placeholder="Select a Roles" class="form-control tagsselector" name="roles[]" multiple="multiple">
  @foreach($roles as $role)
    <option value="{{ $role->id }}"  {{ $role->id == ' ' ? 'selected' : '' }}>{{ $role->name }}</option>
  @endforeach
</select>

I know this part is the issue $role->id == ' ' but i'm not sure what i have to replace with ' '

thanks.

support

Most helpful comment

Try:

$roles = Role::get();

and

<label>Roles</label><br>
<select data-placeholder="Select a Roles" class="form-control tagsselector" name="roles[]" multiple="multiple">
  @foreach($roles as $role)
-    <option value="{{ $role->id }}"  {{ $role->id == ' ' ? 'selected' : '' }}>{{ $role->name }}</option>
+    <option value="{{ $role->id }}"  {{ $user->roles->contains($role->id) ? 'selected' : '' }}>{{ $role->name }}</option>
  @endforeach
</select>

All 5 comments

As the relationship between user and role is many to many so you have to user foreach for user roles.
<select data-placeholder="Select a Roles" class="form-control tagsselector" name="roles[]" multiple="multiple"> @foreach($user->roles as $role) <option value="{{ $role->id }}" {{ $role->id == ' ' ? 'selected' : '' }}>{{ $role->name }}</option> @endforeach </select>

May be you assign just a role for user so you have to select the ->first() laravel function.

@hamidafghan It returns empty

here is my function

$roles = Role::get();

Q. why I get all roles instead of only roles assigned to users?
A. because I might need to add or remove roles to user.

Try:

$roles = Role::get();

and

<label>Roles</label><br>
<select data-placeholder="Select a Roles" class="form-control tagsselector" name="roles[]" multiple="multiple">
  @foreach($roles as $role)
-    <option value="{{ $role->id }}"  {{ $role->id == ' ' ? 'selected' : '' }}>{{ $role->name }}</option>
+    <option value="{{ $role->id }}"  {{ $user->roles->contains($role->id) ? 'selected' : '' }}>{{ $role->name }}</option>
  @endforeach
</select>

@drbyte works perfectly, thank you.

$user

Where did you get the $user from in the foreach ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

neoreids picture neoreids  路  3Comments

bhulsman picture bhulsman  路  3Comments

tripex picture tripex  路  3Comments

notflip picture notflip  路  3Comments