How to add middleware in Laravel route?

Member

by larissa , in category: PHP Frameworks , 2 years ago

How to add middleware in Laravel route?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by raven_corwin , 2 years ago

@larissa 

To add middleware to a route in Laravel, you can use the middleware method on the route definition. Here is an example of how to do it:

1
2
3
Route::get('/users', function () {
    // This route only allows authenticated users
})->middleware('auth');


In the example above, the auth middleware is applied to the route. This middleware will check if the user is authenticated before allowing the request to continue to the route closure.


You can also specify multiple middleware by passing an array of middleware names:

1
2
3
Route::get('/admin', function () {
    // This route only allows authenticated users with the 'admin' role
})->middleware(['auth', 'admin']);


You can also specify middleware on a route group, which will apply the middleware to all routes within the group:

1
2
3
4
5
6
7
8
9
Route::middleware(['auth'])->group(function () {
    Route::get('/users', function () {
        // This route only allows authenticated users
    });

    Route::get('/admin', function () {
        // This route also only allows authenticated users
    });
});


Member

by addison , a year ago

@larissa 

You can add middleware to Laravel routes by following these steps:

  1. Open the web.php or api.php file located in the routes directory of your Laravel project.
  2. Identify the route to which you want to add middleware.
  3. Use the middleware method on the route to specify the middleware you want to apply.


Here's an example of how to add middleware to a route:

1
2
3
Route::get('/example', function () {
    //
})->middleware('middlewareName');


In this example, the middlewareName refers to the name of the middleware class or alias you want to apply to the route. You can also apply multiple middlewares by passing an array of middleware names.


For example:

1
2
3
Route::get('/example', function () {
    //
})->middleware(['middlewareName1', 'middlewareName2']);


Make sure to replace 'middlewareName' with the actual name of the middleware class or alias you want to apply.


You can also create custom middleware in Laravel using the make:middleware Artisan command. This allows you to define your own middleware logic and apply it to routes as needed.