Middleware Support for Specific Methods in Laravel 11.38


In Laravel 11.38, the framework introduces two new methods, middlewareFor
and withoutMiddlewareFor
, allowing developers to apply or exclude middleware for specific methods in resource and singleton routes. This feature, proposed by MrPunyapal in Pull Request #53313, adds precision to middleware assignment.
middlewareFor
and withoutMiddlewareFor
Examples of Below are the examples showcasing how to use these methods.
middlewareFor
Example 1: Applying Middleware with You can assign middleware to specific methods within a resource route using middlewareFor
.
use Illuminate\Support\Facades\Route; Route::resource('users', UserController::class) ->middlewareFor('show', 'auth'); Route::apiResource('users', UserController::class) ->middlewareFor(['show', 'update'], 'auth'); Route::resource('users', UserController::class) ->middlewareFor('show', 'auth') ->middlewareFor('update', 'auth'); Route::apiResource('users', UserController::class) ->middlewareFor(['show', 'update'], ['auth', 'verified']);
Example 2: Applying Middleware to Singleton Routes
The middlewareFor
method works seamlessly with singleton routes as well.
use Illuminate\Support\Facades\Route; Route::singleton('users', UserController::class) ->middlewareFor('show', 'auth'); Route::apiSingleton('users', UserController::class) ->middlewareFor(['show', 'update'], 'auth'); Route::singleton('users', UserController::class) ->middlewareFor('show', 'auth') ->middlewareFor('update', 'auth'); Route::apiSingleton('users', UserController::class) ->middlewareFor(['show', 'update'], ['auth', 'verified']);
withoutMiddlewareFor
Example 3: Removing Middleware with The withoutMiddlewareFor
method excludes middleware from specific methods.
use Illuminate\Support\Facades\Route; Route::middleware('auth', 'verified', 'other')->group(function () { Route::resource('users', UsersController::class)->withoutMiddlewareFor(['create', 'store'], 'verified') ->withoutMiddlewareFor('index', ['auth', 'verified']) ->withoutMiddlewareFor('destroy', 'other'); Route::singleton('user', UserController::class)->withoutMiddlewareFor('show', ['auth', 'verified']) ->withoutMiddlewareFor(['create', 'store'], 'verified') ->withoutMiddlewareFor('destroy', 'other');});
Conclusion
The new middlewareFor
and withoutMiddlewareFor
methods in Laravel 11.38 simplify the process of managing middleware for individual methods in resource and singleton routes. These features provide flexibility and precision in middleware assignment, enhancing the developer experience.
This feature is available starting in Laravel 11.38. For more details, check out the official pull request.
Stay Updated.
I'll you email you as soon as new, fresh content is published.