Update user roles in Laravel

Viewed 292

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

1 Answers
  1. Provide all roles to your page.
  2. Add to User hasRole() method if it does not exists.
  3. Use FormRequest for validation.
  4. Don't forget to get roles with a $user to avoid n+1 queries with User::with('roles')->find($id).
@foreach($allRoles as $role)
    @if(! $user->hasRole($role)) 
        Your form
    @endif
@endforeach
Related