laravel-从http请求获取参数

Gro*_*ler 5 php http angularjs laravel-5

我想将多个参数从Angular应用传递给我的Laravel API,即用户提供的idand choices数组。

角度:

http请求:

    verifyAnswer: function(params) {
            return $http({
                method: 'GET',
                url: 'http://localhost:8888/api/questions/check',
                cache: true,
                params: {
                    id: params.question_id,
                    choices: params.answer_choices
                }
            });
Run Code Online (Sandbox Code Playgroud)

Laravel 5:

route.php:

$router->get('/api/questions/check/(:any)', 'ApiController@getAnswer');
Run Code Online (Sandbox Code Playgroud)

ApiController.php:

public function getAnswer(Request $request) {
    die(print_r($request));
}
Run Code Online (Sandbox Code Playgroud)

我以为我应该:any在URI中使用它来表示要传入各种数据结构的任意数量的参数(id是一个数字,choices是一个Choices数组)。

如何提出此要求?


[200]:/ api / questions / check?choices =选择+1&choices =选择+2&choices =选择+3&id = 1

Ken*_*Ken 7

Laravel 8 更新:

有时您可能希望在不使用查询字符串的情况下传入参数。

前任

Route::get('/accounts/{accountId}', [AccountsController::class, 'showById'])
Run Code Online (Sandbox Code Playgroud)

在您的控制器方法中,您可以使用 Request 实例并使用 route 方法访问参数:

public function showById (Request $request)
{
  $account_id = $request->route('accountId')
  
  //more logic here
}
Run Code Online (Sandbox Code Playgroud)

但是如果您仍然想使用一些查询参数,那么您可以使用相同的 Request 实例并只使用查询方法

Endpoint: https://yoururl.com/foo?accountId=4490
Run Code Online (Sandbox Code Playgroud)
 public function showById (Request $request)
{
  $account_id = $request->query('accountId');
  
  //more logic here
}
Run Code Online (Sandbox Code Playgroud)


chr*_*con 6

更改此:

$router->get('/api/questions/check/(:any)', 'ApiController@getAnswer');
Run Code Online (Sandbox Code Playgroud)

$router->get('/api/questions/check', 'ApiController@getAnswer');
Run Code Online (Sandbox Code Playgroud)

并使用

echo $request->id;
echo $request->choices;
Run Code Online (Sandbox Code Playgroud)

在您的控制器中。无需指定您将接收参数,它们将在$request您注入Request方法时全部存在。