Home > Backend Development > PHP Tutorial > Parameterized Middleware in Laravel

Parameterized Middleware in Laravel

百草
Release: 2025-03-06 02:19:08
Original
370 people have browsed it

Parameterized Middleware in Laravel

Laravel's middleware system gains significant flexibility through parameterization, enabling dynamic behavior based on runtime data. This is especially valuable for scenarios like role-based access control, rate limiting, or any situation demanding configurable middleware logic.

Here's an example demonstrating role-based route protection using parameterized middleware:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class EnsureUserHasRole
{
    public function handle(Request $request, Closure $next, string ...$roles)
    {
        if (!$request->user()?->hasAnyRole($roles)) {
            return response()->json(['error' => 'Insufficient permissions'], 403);
        }
        return $next($request);
    }
}
Copy after login

This middleware checks if the authenticated user possesses any of the specified roles. Let's see how it's used in route definition:

use App\Http\Controllers\PostController;
use App\Http\Middleware\EnsureUserHasRole;

Route::prefix('posts')->group(function () {
    // Public routes
    Route::get('/', [PostController::class, 'index']);

    // Editor routes
    Route::put('/{id}', [PostController::class, 'update'])
        ->middleware(EnsureUserHasRole::class . ':editor');

    Route::post('/', [PostController::class, 'store'])
        ->middleware(EnsureUserHasRole::class . ':editor');

    // Admin routes
    Route::delete('/{id}', [PostController::class, 'destroy'])
        ->middleware(EnsureUserHasRole::class . ':admin');
});
Copy after login

The :editor and :admin parameters passed to the middleware dynamically determine the required roles. This approach maintains clean routes and controllers while implementing sophisticated authorization. The power of parameterized middleware lies in its ability to inject context-specific data into the middleware's logic, resulting in more adaptable and maintainable code.

The above is the detailed content of Parameterized Middleware in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template