To define a route with a custom middleware in Laravel, follow these steps:
routes\web.php
file (for web routes) or routes\api.php
file (for API routes) in your Laravel project.Route
facade to define your route. For example, to define a GET route, use Route::get()
. Choose the appropriate HTTP verb for your route.get()
method. For example, Route::get('/example', ...)
.Route::get('/example', function () {
return response()->json(['message' => 'This is an example route']);
});
Or, you can use a controller method like this:
use App\Http\Controllers\ExampleController;
Route::get('/example', [ExampleController::class, 'index']);
middleware()
method to assign custom middleware to the route. Pass the middleware class or name as the parameter. For example:Route::get('/example', function () {
//
})->middleware('custom-middleware');
Multiple middlewares can be added by passing an array of middleware names:
Route::get('/example', function () {
//
})->middleware(['custom-middleware1', 'custom-middleware2']);
Note: Make sure you have registered your custom middleware in the Kernel
class (app\Http\Kernel.php
file).