我试图在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);
});
});
最后两个路由响应重定向并将该值作为参数发送给控制器,这是我认为最接近直接从路由中执行此操作的