How do you restrict access to routes based on user roles in Laravel?

How do you restrict access to routes based on user roles in Laravel?

In Laravel, restricting access to routes based on user roles is a common approach to implementing authorization. By using middleware, you can easily enforce role-based access control throughout your application. Here’s a detailed guide on how to achieve this:

Step 1: Create the Middleware

First, you need to generate a custom middleware to handle role checking. Use the following Artisan command:

Example

<?php
php artisan make:middleware RoleMiddleware
?>

This will create a RoleMiddleware class in the app/Http/Middleware directory.

Step 2: Define Role-Checking Logic

Next, open the RoleMiddleware.php file and define the logic for checking user roles. Here’s an example of how to implement it:

Example

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RoleMiddleware
{
    public function handle($request, Closure $next, $role)
    {
        // Check if the user is authenticated and has the required role
        if (!Auth::check() || !Auth::user()->hasRole($role)) {
            // Redirect to the home page or show an unauthorized message if the role doesn't match
            return redirect('/home')->with('error', 'You do not have access to this page.');
        }

        // Proceed with the request if the user has the correct role
        return $next($request);
    }
}
?>

Here, the middleware checks if the authenticated user has the necessary role. If not, it redirects them to the /home route with an error message.

Step 3: Register Middleware

Once your middleware is ready, you need to register it in the app/Http/Kernel.php file. In the $routeMiddleware array, add your custom middleware:

Example

<?php
protected $routeMiddleware = [
    // Other middleware
    'role' => \App\Http\Middleware\RoleMiddleware::class,
];
?>

This makes the middleware available for use in your routes.

Step 4: Apply Middleware to Routes

Finally, you can apply the role middleware to routes that require specific role access. For example, if you want to restrict access to an admin page, you can define your route like this:

Example

<?php
Route::get('/admin', [AdminController::class, 'index'])->middleware('role:admin');
?>

In this example, the middleware will ensure that only users with the admin role can access the /admin route.

Bonus: Role Method in User Model

For the middleware to work, you need a hasRole method in your User model. Here’s an example of how you might define it:

Example

<?php
public function hasRole($role)
{
    return $this->role === $role;
}
?>

This simple method checks the user’s role, but you can extend it to work with more complex role management systems, such as assigning multiple roles or using role-based permissions.

Related Questions & Topics