I have data fetching from API and I want to handle errors for that API data because currently if for any reason that data couldn't be fetch my page stops loading and shows error, what I want is if getting api results failed for any reason just set value as null, therefore the rest of page can be loaded just this API data will not.
public function index() {
$myData = ....;
$minutes = 60;
$forecast = Cache::remember('forecast', $minutes, function () {
$app_id = env('HERE_APP_ID');
$app_code = env('HERE_APP_CODE');
$lat = env('HERE_LAT_DEFAULT');
$lng = env('HERE_LNG_DEFAULT');
$url = "https://weather.ls.hereapi.com/weather/1.0/report.json?product=forecast_hourly&name=Chicago&apiKey=$app_code&language=en-US";
$client = new \GuzzleHttp\Client();
$res = $client->get($url);
if ($res->getStatusCode() == 200) {
$j = $res->getBody();
$obj = json_decode($j);
$forecast = $obj->hourlyForecasts->forecastLocation;
}
return $forecast;
});
return view('panel.index', compact('myData', 'forecast'));
}
I want if forecast failed to fetch, data of $forecast be set to null
any idea?