向Laravel路由传递两个参数-资源

7
我将使用资源来构建我的路由,以便可以将两个参数传递到我的资源中。以下是一些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

所以你可以看到,我总是需要参考项目ID,还有电子邮件/文件ID等。

我意识到可以通过手动编写所有路由来完成此操作,但我试图坚持资源模型。

我想这样做可能会起作用吗?

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

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

  });
});
2个回答

9
据我所知,资源方面的内容。
Route::resource('files', 'FileController');

上述资源将会路由以下URL。
针对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

上面提到的单个资源将执行所有列出的路由

除此之外,您必须编写自己的自定义路由

在您的情况下

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"(从file变为files),那么以下路由将会生效...

domain.com/project/100/files/56968

如果是GET请求,将会路由到FileController@show
如果是PUT请求,将会路由到FileController@update
如果是DELETE请求,将会路由到FileController@destroy

这对您提到的任何其他url都没有影响。

请确保使用RESTful资源控制器


1
讲得很清楚,我没有意识到这也会将项目ID传递给方法,但它确实似乎可以工作。谢谢! - amof

5

对于像'/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"
]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接