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

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

问题描述:

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.

我想在此提出您的意见,或者也许是您最熟悉的将中间件分配给Laravel路由的做法。 我已经阅读了3种方法: p>

  • 数组(单个和多个) p>

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

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

  • 链方法 p>

    Route :: get('/',function(){ // }) - > 中间件(['first','second']); code> p> li>

  • 完全限定的类名 p>

    使用App \ Http \ Middleware \ FooMiddleware; Route :: get('admin / profile',['middleware'=> FooMiddleware :: class,function(){ // }]); 代码> p> li> ul>

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

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

});