Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 391
Mr.Unknown Avatar asked Jun 26 '16 13:06

Mr.Unknown


2 Answers

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']);
like image 172
rroy Avatar answered Sep 20 '22 12:09

rroy


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

});
like image 43
herrjeh42 Avatar answered Sep 22 '22 12:09

herrjeh42