【问题标题】:Passing 2 Parameters to Laravel Routes - Resources将 2 个参数传递给 Laravel 路由 - 资源
【发布时间】:2015-01-25 22:02:55
【问题描述】:

我正在尝试使用资源来构建我的路线,以便我可以将两个参数传递给我的资源。

我会举几个例子来说明 URL 的外观:

domain.com/dashboard
domain.com/projects
domain.com/project/100
domain.com/project/100/emails
domain.com/project/100/email/3210
domain.com/project/100/files
domain.com/project/100/file/56968

所以你可以看到我总是需要参考 project_id 以及电子邮件/文件 ID 等。

我意识到我可以通过手动编写所有路线来手动执行此操作,但我正在尝试坚持资源模型。

我认为这样的方法可能有效?

Route::group(['prefix' => 'project'], function(){
  Route::group(['prefix' => '{project_id}'], function($project_id){

    // Files
    Route::resource('files', 'FileController');

  });
});

【问题讨论】:

    标签: php laravel routes resources


    【解决方案1】:

    据我所知的资源

    Route::resource('files', 'FileController');
    

    上述资源将路由以下网址。

    资源控制器为您的 Route::resource('files', 'FileController'); 处理的操作很少

    Route::get('files',FileController@index) // get req will be routed to the index() function in your controller
    Route::get('files/{val}',FileController@show) // get req with val will be routed to the show() function in your controller
    Route::post('files',FileController@store) // post req will be routed to the store() function in your controller
    Route::put('files/{id}',FileController@update) // put req with id will be routed to the update() function in your controller
    Route::delete('files',FileController@destroy) // delete req will be routed to the destroy() function in your controller
    

    上面提到的单个resource 将完成所有列出的routing

    除了那些你必须写你的custom route

    在你的场景中

    Route::group(['prefix' => 'project'], function(){
      Route::group(['prefix' => '{project_id}'], function($project_id){
    
        // Files
        Route::resource('files', 'FileController');
    
      });
    }); 
    

    domain.com/project/100/files

    如果它的get请求将被路由到FileController@index
    如果它的post请求将被路由到FileController@store

    如果您的“domain.com/project/100/file/56968”更改为“domain.com/project/100/files/56968(文件到文件),则会发生以下生根...

    domain.com/project/100/files/56968

    如果是get请求将被路由到FileController@show
    如果它是put请求将被路由到FileController@update
    如果它是@ 987654341@ 请求将被路由到FileController@destroy

    它对你提到的任何其他urls 没有影响

    提供,你需要有RESTful Resource Controllers

    【讨论】:

    • 这很好解释,我没有意识到这也会将项目 id 传递给方法,但它确实似乎有效。谢谢!
    【解决方案2】:

    对于像'/project/100/file/56968'这样的请求,你必须像这样指定你的路由:

    Route::resource('project.file', 'FileController');
    

    然后就可以在控制器的show方法中获取参数了:

    public function show($project, $file) {
        dd([
            '$project' => $project,
            '$file' => $file
        ]);
    }
    

    这个例子的结果是:

    array:2 [▼
      "$project" => "100"
      "$file" => "56968"
    ]
    

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 2018-06-17
      • 2019-03-03
      • 2018-08-14
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      相关资源
      最近更新 更多