如何将中间件分配给 Laravel 中的路由(更好的方式)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38039159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:04:05  来源:igfitidea点击:

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

phplaravelroutesframeworksmiddleware

提问by Mr.Unknown

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:

我想在这里提供您的意见,或者您在 Laravel 中将中间件分配给路由的最佳实践。我已经阅读了 3 种方式:

  • 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 () { // }]);

  • 数组(单个和多个)

    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.

我只想知道你知道的最佳实践是什么,如果可能的话,添加一些参考资料,以便我们新手更容易理解。任何答案将不胜感激。

回答by rroy

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

从我的角度来看,我更喜欢将中间件分配给任何路由的链方法,因为它看起来非常干净和简单。IE,

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

回答by herrjeh42

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

});