I have three user roles: Student, Teacher, Admin.
If a user is a student I want to display the option to Elevate them to either Teacher or Admin in a dropdown and the same for the other roles eg. Teacher gets Admin and Student option.
Currently this looks like this:
Index
@if ($user->role == 'admin')
<form action="/admin/users/{{ $user->id }}" method="POST">
@csrf
@method('PATCH')
<input class="hidden" name="role" value="user">
<button>Make User</button>
</form>
@else
<form action="/admin/users/{{ $user->id }}" method="POST">
@csrf
@method('PATCH')
<input class="hidden" name="role"value="teacher">
<button>Make Teacher</button>
</form>
@endif
Controller
public function update(User $user)
{
$attributes = request()->validate([
'role' => ['required', Rule::exists('users', 'role')]
]);
$user->update($attributes);
return back()->with('success', 'User Updated!');
}
How would I be able to do an if statement to list all the roles except for the current role assigned to the user or perhaps this is better done in the controller instead?
And is it possible to put the role in a slug and then run a foreach so I don't repeat code?
Im new top Laravel so any help would be appreciated :) Thanks
hasRole()
method if it does not exists.$user
to avoid n+1 queries with User::with('roles')->find($id)
.@foreach($allRoles as $role)
@if(! $user->hasRole($role))
Your form
@endif
@endforeach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.