Problem with Twitch API in Laravel - Encountering Non-Object Error

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?

You’re getting this error because you’re trying to access properties on a null object when the streamer’s offline. Sure, you check if $response->stream == null, but then you still try to grab $response->stream->preview->large and $response->stream->channel->game anyway. Move those thumbnail and game_title assignments inside your conditional block - only run them when the stream’s actually live. Handle online and offline states separately. Also heads up - the Kraken API’s deprecated, so you’ll want to switch to the Helix API soon to avoid headaches down the road.