[英]laravel - get parameters from http request
I want to pass in multiple parameters from my Angular app to my Laravel API, namely the id
and choices
array supplied by user.我想将多个参数从我的 Angular 应用程序传递到我的 Laravel API,即用户提供的
id
和choices
数组。
Angular:角度:
http request: 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
}
});
Laravel 5: Laravel 5:
routes.php:路线.php:
$router->get('/api/questions/check/(:any)', 'ApiController@getAnswer');
ApiController.php: ApiController.php:
public function getAnswer(Request $request) {
die(print_r($request));
}
I thought I should use :any
within my URI to indicate I'll be passing in an arbitrary amount of parameters of various data structure (id is a number, choices is an array of choices).我想我应该在我的 URI 中使用
:any
来表示我将传入任意数量的各种数据结构的参数(id 是一个数字,choices 是一个选项数组)。
How can I make this request?我怎样才能提出这个要求?
[200]: /api/questions/check?choices= choice+1 &choices= choice+2 &choices= choice+3 &id=1
[200]:/api/questions/check?choices=choice+1 &choices=choice+2 &choices=choice+3 &id=1
Update for Laravel 8: Laravel 8 更新:
Sometimes you may want to pass in parameters without using query strings.有时您可能希望在不使用查询字符串的情况下传入参数。
EX前任
Route::get('/accounts/{accountId}', [AccountsController::class, 'showById'])
In your controllers method, you can use a Request instance and access the parameters like so using the route method:在您的控制器方法中,您可以使用 Request 实例并使用 route 方法访问参数:
public function showById (Request $request)
{
$account_id = $request->route('accountId')
//more logic here
}
But if you still wanted to use some query params then you can use that same Request instance and just use the query method但是如果您仍然想使用一些查询参数,那么您可以使用相同的 Request 实例并只使用查询方法
Endpoint: https://yoururl.com/foo?accountId=4490
public function showById (Request $request)
{
$account_id = $request->query('accountId');
//more logic here
}
Change this: 改变这个:
$router->get('/api/questions/check/(:any)', 'ApiController@getAnswer');
to 至
$router->get('/api/questions/check', 'ApiController@getAnswer');
And fetch the values with 并使用获取值
echo $request->id;
echo $request->choices;
in your controller. 在你的控制器中。 There is no need to specify that you will receive parameters, they will all be in
$request
when you inject Request
to your method. 没有必要指定您将接收参数,当您向方法注入
Request
时,它们都将在$request
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.