I’m developing a Laravel project that keeps track of streamers and shows whether they are currently live or not. I’m using the Twitch API to verify if a streamer is online and then update the relevant entries in my database.
Lately, I’ve been facing an issue where I receive this error message when the streamer isn’t live:
Trying to get property of non-object
Here’s the code I have in my scheduled task:
$response = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.$streamer->channel));
if($response->stream == null) $isLive = 0;
else $isLive = 1;
$streamUpdate = Streams::where('id', $streamer->id)->firstOrFail();
$streamUpdate->thumbnail = $response->stream->preview->large;
$streamUpdate->game_title = $response->stream->channel->game;
$streamUpdate->status = $isLive;
$streamUpdate->save();
When a streamer is offline, the API returns the following:
{"stream":null,"_links":{"self":"https://api.twitch.tv/kraken/streams/example","channel":"https://api.twitch.tv/kraken/channels/example"}}
Can anyone help me understand why I’m encountering this non-object error and how I can resolve it?