How to assign Middleware to Routes in Laravel (better way)?

17,837

Solution 1

From my point of view, I prefer the chain method to assign middleware to any route as it looks so clean and easier. i.e,

Route::get('/', function () {
        //
})->middleware(['first', 'second']);

Solution 2

From my point of view all versions are ok and I can't think of any advantages from one over the other. I like to group them like this.

Route::group(['middleware' => 'auth'], function () {

    Route::get('/home', [
        'as' => 'home',
        'uses' => 'Dashboard\DashboardController@dashboard'
    ]);  

    Route::pattern('users', '\d+');
    Route::resource('users','UserController'); 

   // more route definitions

});
Share:
17,837
Mr.Unknown
Author by

Mr.Unknown

Aspiring Web Developer and Cyber Security Enthusiast I love creating Websites as well as teaching others what I know about Information Technology.

Updated on June 04, 2022

Comments

  • Mr.Unknown
    Mr.Unknown almost 2 years

    I would like to here your opinion or maybe your best known practice in assigning Middleware to Routes in Laravel. I have read 3 ways:

    • Array (Single and Multiple)

      Route::get('/',['middlware' => 'auth', function () { // Code goes here }]);

      Route::get('/', ['middleware' => ['first', 'second'], function () { // }]);

    • Chain Method

      Route::get('/', function () { // })->middleware(['first', 'second']);

    • Fully Qualified Class Name

      use App\Http\Middleware\FooMiddleware; Route::get('admin/profile', ['middleware' => FooMiddleware::class, function () { // }]);

    I just wanna know what is the best practices you know and if possible add some reference so that it is easier for us newbie to understand. Any answer will be appreciated.