![](/img/trans.png)
[英]How to pass post parameters in laravel from the route to the controller?
[英]How to pass extra parameters to controller from Laravel route
我正在嘗試對Laravel路線中的API調用進行基本驗證。 這是我要實現的目標:
Route::group(['prefix' => 'api/v1/properties/'], function () {
Route::get('purchased', 'PropertiesController@getPropertyByProgressStatus', function () {
//pass variable x = 1 to the controller
});
Route::get('waiting', 'PropertiesController@getPropertyByProgressStatus', function () {
//pass variable x = 2 to the controller
});
});
長話短說,取決於api / v1 / properties /之后的URI段,我想將其他參數傳遞給控制器。 有沒有辦法做到這一點?
我能夠將其與以下route.php文件一起使用:
Route::group(['prefix' => 'api/v1/properties/'], function () {
Route::get('purchased', [
'uses' => 'PropertiesController@getPropertyByProgressStatus', 'progressStatusId' => 1
]);
Route::get('remodeled', [
'uses' => 'PropertiesController@getPropertyByProgressStatus', 'progressStatusId' => 1
]);
Route::get('pending', [
'uses' => 'PropertiesController@getPropertyByProgressStatus', 'progressStatusId' => 3
]);
Route::get('available', [
'uses' => 'PropertiesController@getPropertyByProgressStatus', 'progressStatusId' => 4
]);
Route::get('unavailable', [
'uses' => 'PropertiesController@getPropertyByProgressStatus', 'progressStatusId' => 5
]);
});
以及控制器中的以下代碼:
公共函數getPropertyByProgressStatus(\\ Illuminate \\ Http \\ Request $ request){
$action = $request->route()->getAction();
print_r($action);
$ action變量幾乎可以讓我訪問從路由傳遞的額外參數。
我認為您可以直接在控制器中執行此操作,並將該值作為路由的參數接收:
首先,您需要在控制器中指定參數的名稱。
Route::group(['prefix' => 'api/v1/properties/'], function ()
{
Route::get('{parameter}', PropertiesController@getPropertyByProgressStatus');
這樣,getPropertyByProgressStatus方法將接收此值,因此在控制器中:
class PropertiesController{
....
public function getPropertyByProgressStatus($parameter)
{
if($parameter === 'purchased')
{
//do what you need
}
elseif($parameter === 'waiting')
{
//Do another stuff
}
....
}
我希望它有助於解決您的問題。
查看以下課程: 學習Laravel或使用Laravel創建RESTful API
最好的祝願。
-----------已編輯---------------您可以重定向到所需的路由:
Route::group(['prefix' => 'api/v1/properties/'], function () {
Route::get('purchased', function () {
return redirect('/api/v1/properties/purchased/valueToSend');
});
Route::get('waiting', function () {
return redirect('/api/v1/properties/waiting/valueToSend');
});
Route::get('purchased/{valueToSend}', PropertiesController@getPropertyByProgressStatus);
});
Route::get('waiting/{valueToSend}', PropertiesController@getPropertyByProgressStatus);
});
});
最后兩條路由響應重定向並將該值作為參數發送給控制器,這是我認為最直接從路由執行此操作的最接近的路由。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.