Courses

Roles and Permissions in Laravel 11

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...

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 68 courses (1188 lessons, 43 h 18 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord