Reputation: 180
I am still learning Laravel so bear with me.
I am trying to call a specific data from external API, I managed to get the data from the external API by using Http as showing below:
Controller:
public function index()
{
$apiURL = 'http://example.com/api/Order/';
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'segseg435324534...',
];
$response = Http::withHeaders($headers)->get($apiURL);
$data = $response->json();
return view('job.index',compact ('data'));
}
And here is web.php:
Route::resource('job', 'App\Http\Controllers\AjaxController');
So far until here everything is working fine and I am getting the data from the external API and inside foreach.
Usually when I work on CRUD application with MySQL I need to do something like:
public function show($id)
{
$jobs = Jobs::find($id);
return view('jobs.show', compact('jobs'));
}
And then pass as showing below:
<a href="{{ route('jobs.show',$job->id)}}"></a>
So in the above code I am getting the "id" from the model but in my case now there is no model because the API is external.
Is it possible to achieve this without model by passing the parameter to the URL using Http, and do I need to create different route for it?
Update:
After modify the controller from the answer below I faced another problem:
public function show($id)
{
$apiURL = 'http://example.com/api/Order/';
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'segseg435324534...',
];
$response = Http::withHeaders($headers)->get($apiURL, [
'id' => $id,
]);
$data = $response->json();
return view('job.show',compact ('data'));
}
I tried this but when I display data inside the view like this:
<td>{{ $data['Description'] }}</td>
it shows this error:
Undefined array key "Description"
and when I return dd($data)
it return all the data from the external API.
Note: this is how I redirect to the above view:
{{ route('job.show',$item['DocNo'])}}
Edit 2:
dd($data) resutls:
array:236 [▼
0 => {#1459 ▶}
1 => {#1462 ▶}
2 => {#1489 ▶}
3 => {#1483 ▶}
4 => {#1468 ▶}
5 => {#1466 ▶}
6 => {#1464 ▶}
7 => {#1476 ▶}
8 => {#1473 ▶}
9 => {#1481 ▶}
10 => {#1492 ▶}
11 => {#1479 ▶}
Upvotes: 1
Views: 3633
Reputation: 564
Laravel 8 Http client url parameter can't pass like this and it's not adding to the url. My endpoint is like api/user/{id}
$response = Http::::withHeaders($headers)->get($apiURL, [
'id' => $id
]);
instead of above option I tried like below. maybe someone can help this out.
$apiURL = 'api/user/'.{id};
$response = Http::::withHeaders($headers)->get($apiURL);
Upvotes: 0
Reputation: 957
To add parameter to Http client:
$response = Http::::withHeaders($headers)->get($apiURL, [
'id' => $id,
'some_another_parameter' => $param
]);
As error said you don't have Description
key for response array ($data
). You have to foreach $data
to access your desired key like:
@foreach($data as $data)
<td>{{ $data['Description'] }}</td>
@endforeach
Upvotes: 1