2015-10-24 54 views
0

我試圖處理Laravel路由中的API調用的基本驗證。這裏是我想要實現的:如何從Laravel路由傳遞額外的參數給控制器

Route::group(['prefix' => 'api/v1/properties/'], function() { 
    Route::get('purchased', '[email protected]', function() { 
     //pass variable x = 1 to the controller 
    }); 

    Route::get('waiting', '[email protected]', function() { 
     //pass variable x = 2 to the controller 
}); 

});

長話短說,取決於api/v1/properties /之後URI的段,我想將不同的參數傳遞給控制器​​。有沒有辦法做到這一點?

回答

0

我認爲你可以在控制器中直接這樣做,並接收該值作爲路線的參數:

首先,你需要一個控制器指定的參數的名稱。

Route::group(['prefix' => 'api/v1/properties/'], function() 
{ 
    Route::get('{parameter}', [email protected]'); 

這樣的getPropertyByProgressStatus方法會在控制器接收這個值,所以:

class PropertiesController{ 
.... 
public function getPropertyByProgressStatus($parameter) 
{ 
    if($parameter === 'purchased') 
    { 
     //do what you need 
    } 
    elseif($parameter === 'waiting') 
    { 
     //Do another stuff 
    } 
.... 
} 

我希望這有助於解決您的問題。

乘坐查看該課程:Learn LaravelCreate a RESTful API with Laravel

最良好的祝願。

-----------編輯--------------- 您可以重定向到所需的路線:

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}', [email protected]); 
    }); 

    Route::get('waiting/{valueToSend}', [email protected]); 
    }); 
}); 

的最後兩條路由對重定向做出響應,並將該值作爲參數發送給控制器,這是我認爲直接從路由直接執行此操作的最接近的路由。

+0

是的,問題是我該如何做到這一點?正如我在問題中提到的那樣:「我試圖在Laravel的路線中處理我的API調用的基本驗證」。感謝 – user1029829

+0

好吧,基本上你是在路線中做的,檢查你是否收到一個參數併發送給控制器。它對你沒用嗎?請詳細說明爲什麼它不起作用。最好的祝願。 PS:您可以將重定向返回到其他路線。 CHeck的迴應(編輯) – JuanDMeGon

+0

仍然不是我想要得到的。看看這段代碼:Route :: get('api/v1/properties/purchased','PropertiesController @ getPropertyById',function($ variableX){});我如何修改$ variableX來傳遞1呢? – user1029829

0

我能得到它具有以下route.php文件工作:

Route::group(['prefix' => 'api/v1/properties/'], function() { 
    Route::get('purchased', [ 
     'uses' => '[email protected]', 'progressStatusId' => 1 
    ]); 
    Route::get('remodeled', [ 
     'uses' => '[email protected]', 'progressStatusId' => 1 
    ]); 
    Route::get('pending', [ 
     'uses' => '[email protected]', 'progressStatusId' => 3 
    ]); 
    Route::get('available', [ 
     'uses' => '[email protected]', 'progressStatusId' => 4 
    ]); 
    Route::get('unavailable', [ 
     'uses' => '[email protected]', 'progressStatusId' => 5 
    ]); 
}); 

,並在控制器下面的代碼:

公共職能getPropertyByProgressStatus(\照亮\ HTTP \ $申請請求){

$action = $request->route()->getAction(); 
print_r($action); 

很多$ action變量會讓我訪問我從路由傳遞的額外參數。

相關問題