How to add middleware in Laravel route?

Member

by larissa , in category: PHP Frameworks , 9 months ago

How to add middleware in Laravel route?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 3 months 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
    });
});