簡體   English   中英

將2個參數傳遞給Laravel路徑 - 資源

[英]Passing 2 Parameters to Laravel Routes - Resources

我正在嘗試使用資源構建我的路由,以便我可以將兩個參數傳遞到我的資源中。

我將舉幾個URLS的外觀示例:

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');

  });
});

據我所知,資源

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

上面提到的資源將路由以下網址。

資源控制器為您的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
如果它的delete請求將被路由到FileController@destroy

它對你提到的任何其他url都沒有影響

提供,您需要具有RESTful資源控制器

對於像'/ 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"
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM