How to set up middleware in laravel?


by lottie , in category: PHP Frameworks , 6 months ago

How to set up middleware in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 6 months ago


To set up middleware in Laravel, follow these steps:

  1. Open the terminal and navigate to your Laravel project directory.
  2. Run the command php artisan make:middleware MyMiddleware to generate a new middleware file. Replace MyMiddleware with your desired middleware name.
  3. After generating the middleware, open the newly created file located in the app/Http/Middleware directory. This file contains two methods: handle and terminate. The handle method is where you can add your custom logic. For example, you can check for authentication, roles, or permissions before executing the requested route. The terminate method is called after a response has been sent to the browser. You can perform any additional cleanup or logging tasks here.
  4. Register your middleware in the app/Http/Kernel.php file. In the $routeMiddleware array, add a new key-value pair, such as 'my-middleware' => AppHttpMiddlewareMyMiddleware::class. This key-value pair allows you to reference your middleware using the key value ('my-middleware') later on.
  5. To apply the middleware to a route or group of routes, you have two options: Option 1: Apply it to an individual route in the routes/web.php or routes/api.php file like this: Route::get('/example', function () {})->middleware('my-middleware');. Replace my-middleware with the key created in step 4. Option 2: Apply it to a group of routes. In the same routes/web.php or routes/api.php file, group the routes using the middleware method like this: Route::middleware(['my-middleware'])->group(function () { // Your routes here }); Replace 'my-middleware' with the key created in step 4.
  6. Save the changes and test your middleware by accessing the route(s) to which you applied it. The middleware logic will be executed before these routes are accessed.