How to define a route with a custom middleware in Laravel?

To define a route with a custom middleware in Laravel, follow these steps:

  1. Open the routes\web.php file (for web routes) or routes\api.php file (for API routes) in your Laravel project.
  2. Use the Route facade to define your route. For example, to define a GET route, use Route::get(). Choose the appropriate HTTP verb for your route.
  3. Pass the URL path as the first parameter to the get() method. For example, Route::get('/example', ...).
  4. As the second parameter, pass a callback function or a controller method to handle the request when this route is accessed. For example, you can use a closure like this:
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']);
  1. After the callback function or controller method, chain the 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).