Laravel 5 Laravel 5.4路线简化

Laravel 5 Laravel 5.4路线简化,laravel-5,url-routing,nested-resources,Laravel 5,Url Routing,Nested Resources,我一直在试图找到一些关于如何完成以下任务的文档,但似乎我没有使用正确的搜索词 我想在Laravel 5.4中通过从路径中省略路由名称来实现一些简化路由,例如: /{page}而不是/pages/{page} /profile而不是/users/{user}/edit /{exam}/{question}(甚至/exams/{exam}/{question})而不是/exams/{exams}/questions/{question} 当前路线示例 Route::resource('exams.q

我一直在试图找到一些关于如何完成以下任务的文档,但似乎我没有使用正确的搜索词

我想在Laravel 5.4中通过从路径中省略路由名称来实现一些简化路由,例如:

  • /{page}
    而不是
    /pages/{page}
  • /profile
    而不是
    /users/{user}/edit
  • /{exam}/{question}
    (甚至
    /exams/{exam}/{question}
    )而不是
    /exams/{exams}/questions/{question}
  • 当前路线示例

    Route::resource('exams.questions', 'ExamQuestionController', ['only' => ['show']]);
    // exams/{exam}/question/{question}
    
    我知道如何使用路由关闭和一次性路由(例如:
    route::get…
    )实现这一点,但有没有办法使用
    route::resource

    rails
    中,可以通过以下方式完成上述操作:

    resources :exams, path: '', only: [:index, :show] do
      resources :question, path: '', only: [:show]
    end
    
    // /:exam_id/:id
    
    不,您不能也不应该尝试使用
    Route::resource
    执行此操作

    Route::resource
    的全部目的是,它以与常见的“RESTful路由”模式匹配的特定方式创建路由

    想要更简单的路由没有什么错(没有人强迫您使用RESTful路由),但是您需要自己使用
    Route::get
    ,等等,如您所知

    来自(不完全是您的案例,但与之相关-表明
    Route::resource
    并不意味着超级可配置):

    补充资源控制器 如果需要向资源控制器添加默认资源路由集之外的其他路由,则应在调用Route::resource之前定义这些路由;否则,资源方法定义的路由可能会无意中优先于补充路由:

    Route::get('photos/popular', 'PhotoController@method');
    
    Route::resource('photos', 'PhotoController');
    

    虽然我还没有找到一种严格使用
    Route::resource
    来完成测试用例的方法,但我实现了以下内容来完成我的尝试:

    // For: `/{exam}/{question}`
    Route::group(['as' => 'exams.', 'prefix' => '{exam}'], function() {
      Route::get('{question}', [
        'as'      => 'question.show',
        'uses'    => 'QuestionController@show'
      ]);
    });
    
    // For: `/exams/{exam}/{question}`
    Route::group(['as' => 'exams.', 'prefix' => 'exams/{exam}'], function() {
      Route::get('{question}', [
        'as'      => 'question.show',
        'uses'    => 'QuestionController@show'
      ]);
    });
    
    // For: `/profile`
    Route::get('profile', function() {
      $controller = resolve('App\Http\Controllers\UserController');
      return $controller->callAction('edit', $user = [ Auth::user() ]);
    })->middleware('auth')->name('users.edit');
    
    // For: `/{page}`
    // -------------- 
    // Note that the above `/profile` route must come before 
    // this route if using both methods as this route
    // will capture `/profile` as a `{page}` otherwise
    Route::get('{page}', [
      'as'      => 'page.show',
      'uses'    => 'PageController@show'
    ]);