Reputation: 10115
Below is the class that returns Country data
class CountryData {
public function GetCountries() {
return response()->json(['Data' => \App\Models\CountryModel::all()]);
}
}
I have following Json Data returned by above function
HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json
{
"Data":[
{
"CountryID" : 1,
"Country" : "United States",
"CountryCode": "US"
}
]
}
Below is the code in Controller.
$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));
Below is the code in View
@foreach($Countries["Data"] as $Country)
<tr class="odd pointer">
<td class=" ">{{$Country["Country"]}}</td>
<td class=" ">{{$Country["CountryCode"]}}</td>
</tr>
@endforeach
When I type echo $Countries;
I get above text. When I type echo json_decode($Countries, true);
It shows blank. Can you please guide me why this is happening?
Reason I am doing this because data is being passed into Blade using below code.
$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));
Upvotes: 3
Views: 10627
Reputation: 10115
Below should be the controller code:
return view('Country.List')->with('Countries', $Countries->getData()->Data);
^^^^^^^^^^^^^^^
But I am not sure if this is correct way to fix this issue. I am reading JsonResponse
.
Upvotes: 1
Reputation: 235
You need to add true in the json_decode($data,true) function. Change this
$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries));
Change to
$Countries = (new \App\DataAccess\CountryData())->GetCountries();
return view('Country.List')->with('Countries', json_decode($Countries,true));
View
@foreach($Countries["Data"] as $Country)
<tr class="odd pointer">
<td class=" ">{{$Country["Country"]}}</td>
<td class=" ">{{$Country["CountryCode"]}}</td>
</tr>
@endforeach
Upvotes: 0