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.
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 ?
Most helpful comment
Try:
$roles = Role::get();and