i'm having a small problem when updating my streams on my laravel project, i'm trying to define if the streamer is live or not and hide if theyr not in my application however when there is a streamer that is not live it gives me..
Trying to get property of non-object
My cronjob postback looks like this:
$twitch_api = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.$stream->channel));
if($twitch_api->stream == null) $live = 0;
else $live = 1;
$update = Streams::where('id', $stream->id)->firstOrFail();
$update->thumb = $twitch_api->stream->preview->large;
$update->game = $twitch_api->stream->channel->game;
$update->status = $live;
$update->save();
The Twitch API when offline it displayes this...
{"stream":null,"_links":{"self":"https://api.twitch.tv/kraken/streams/chan","channel":"https://api.twitch.tv/kraken/channels/chan"}}
Any idea why it gives me non-object?
Thanks!
When the stream is offline and "stream":null
the following lines of your code will not work:
$update->thumb = $twitch_api->stream->preview->large;
$update->game = $twitch_api->stream->channel->game;
You need to encapsulate that in an if
or case
statement so that it doesn't run that when the stream is offline. You are already setting $live
to 1 if it is live, you just need to use that later on in a control statement.
something like this:
$twitch_api = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.$stream->channel));
if($twitch_api->stream == null) $live = 0;
else $live = 1;
$update = Streams::where('id', $stream->id)->firstOrFail();
switch($live){
case 0:
// do stuff when the stream is offline
break;
case 1:
// do stuff when the stream is online
$update->thumb = $twitch_api->stream->preview->large;
$update->game = $twitch_api->stream->channel->game;
break;
}
$update->status = $live;
$update->save();