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:
http request:
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:
routes.php:
$router->get('/api/questions/check/(:any)', 'ApiController@getAnswer');
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).
How can I make this request?
[200]: /api/questions/check?choices= choice+1 &choices= choice+2 &choices= choice+3 &id=1
To retrieve the query parameters on your Laravel backend, you can make use of either the "Request" class or the "request()" helper method. Imagine you want to get the "search" query from the URL, you can do as follows. $searchQuery = $request->query('search');
You can pass query string to URL in laravel using named route and controller action. You can pass query string as comma separated array to named route and controller action and redirect to URL.
Introduction. Laravel provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications.
Update for 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:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With