phplaravelroutesframeworksmiddleware

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


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:

Route::get('/',['middlware' => 'auth', function () {
    // Code goes here
}]);
Route::get('/', ['middleware' => ['first', 'second'], function () {
    //
}]);
Route::get('/', function () {
    //
})->middleware(['first', 'second']);
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.


Solution

  • 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']);