Courses

Roles and Permissions in Laravel 11

Managing Users: Staff / Doctors / Patients

Summary of this lesson:
- Managing clinic users with role restrictions
- Implementing role-based user listing
- Setting up user policies for viewing and creation
- Writing tests for user management permissions
- Setting up form validation for user creation

The Clinic Owner's role involves managing users on their team and handling the creation of doctor/staff/patient users.

So, let's create two functions—list and create users—similarly to how we did it for the teams.

First, the Policy:

php artisan make:policy UserPolicy

app/Policies/UserPolicy.php

use App\Models\User;
use App\Enums\Permission;
use Illuminate\Auth\Access\HandlesAuthorization;
 
class UserPolicy
{
use HandlesAuthorization;
 
public function viewAny(User $user): bool
{
return $user->hasPermissionTo(Permission::LIST_USER);
}
 
public function create(User $user): bool
{
return $user->hasPermissionTo(Permission::CREATE_USER);
}
}

Now, we can use that ' viewAnyandcreatein the Controller withGate::authorize()`, right?

But first, let's create a Form Request.

php artisan make:request StoreUserRequest

Here are the validation rules:

app/Http/Requests/StoreUserRequest.php

use Illuminate\Validation\Rules\Password;
use Illuminate\Foundation\Http\FormRequest;
 
class StoreUserRequest extends FormRequest
{
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', Password::defaults()],
'role_id' => ['required', 'integer', 'exists:roles,id'],
];
}
 
public function authorize(): bool
{
return true;
}
}

Next, the Controller.

php artisan make:controller UserController

Here's the code for the methods...

The full lesson is only for Premium Members.
Want to access all 13 lessons of this course? (96 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord