To implement user roles in Laravel, you can follow these best practices:
-
Database Design: Create a
rolestable and a pivot tablerole_userto establish a many-to-many relationship between users and roles.// Migration for roles table Schema::create('roles', function (Blueprint $table) { $table->id(); $table->string('name')->unique(); $table->timestamps(); }); // Migration for role_user pivot table Schema::create('role_user', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->foreignId('role_id')->constrained()->onDelete('cascade'); $table->timestamps(); }); -
Define Relationships: In your
Usermodel, define the relationship to roles.class User extends Authenticatable { public function roles() { return $this->belongsToMany(Role::class); } public function hasRole($role) { return $this->roles()->where('name', $role)->exists(); } } -
Assign Roles: You can assign roles to users using the relationship.
$user = User::find(1); $role = Role::where('name', 'admin')->first(); $user->roles()->attach($role); -
Authorization: Use middleware to restrict access based on roles.
-
Create a middleware:
php artisan make:middleware RoleMiddleware -
Implement the middleware logic:
public function handle($request, Closure $next, $role) { if (!auth()->check() || !auth()->user()->hasRole($role)) { abort(403, 'Unauthorized'); } return $next($request); } -
Register the middleware in
app/Http/Kernel.php:protected $routeMiddleware = [ // ... 'role' => \App\Http\Middleware\RoleMiddleware::class, ];
-
-
Apply Middleware to Routes: Use the middleware in your routes to protect them.
Route::group(['middleware' => ['role:admin']], function () { Route::get('/admin', [AdminController::class, 'index']); }); -
Policy and Gates: For more granular control, consider using Laravel's policies and gates.
-
Define a policy:
php artisan make:policy UserPolicy -
Implement the policy methods:
public function viewAdminDashboard(User $user) { return $user->hasRole('admin'); } -
Register the policy in
AuthServiceProvider:protected $policies = [ User::class => UserPolicy::class, ]; -
Use the policy in controllers:
$this->authorize('viewAdminDashboard', User::class);
-
By following these steps, you can effectively manage user roles and permissions in your Laravel application, ensuring that users can only perform actions specific to their roles.