How to Add Middleware to a Group Of Routes in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to add middleware to a group of routes in Laravel

 

How to add middleware to a group of routes in laravel

To add middleware to a group of routes in Laravel, you can use the `middleware()` method.

Here's an example:

Route::middleware(['auth'])->group(function () {
    Route::get('dashboard', function () {
        // Only authenticated users can access this route
        return view('dashboard');
    });

    Route::get('profile', function () {
        // Only authenticated users can access this route
        return view('profile');
    });
});

 

In the above example, we have created a group of routes using the `group()` method. We have also added the `auth` middleware to the group using the `middleware()` method. This means that any route inside the group can only be accessed by an authenticated user.

You can add any middleware to the group by passing its name as a string to the `middleware()` method. If you need to add multiple middleware to the group, you can pass an array of middleware names to the method like this:

Route::middleware(['auth', 'verified'])->group(function () {
    // Routes inside the group
});

 

In the above example, we have added two middleware to the group: auth and verified.

Comments 0

Leave a comment