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 show 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 ▶}
CodePudding user response:
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