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.
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']);
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With