i confused with my apps, i have a problem with displaying image_url data from Twitter API.
CONTROLLER
$events = Event::findOrFail($id);
$query = $events->hashtag;
// Application Programming Interface
$stack = HandlerStack::create();
$middleware = new Oauth1([
'consumer_key' => 'CONSUMER_KEY',
'consumer_secret' => 'CONSUMER_SECRET',
'token' => 'TOKEN',
'token_secret' => 'TOKEN_SECRET'
]);
$stack->push($middleware);
$client = new Client([
'base_uri' => 'https://api.twitter.com/1.1/',
'handler' => $stack,
'auth' => 'oauth'
]);
$res = $client->get('https://api.twitter.com/1.1/search/tweets.json?q=%23', [
'query' => ['q' => $query]
]);
$array = json_decode($res->getBody()->getContents(), true);
$tes = (count($array['statuses']));
if($request->user()->cannot('show', $events)){
abort(405);
}else{
return view('dashboard.events.show', compact('events'), [
'events' => $events
])->with([
'array'=> $array,
'tes' => $tes
]);
}
VIEW
@for ($i = 0; $i < $tes; $i++)
<div class="col-md-4">
<img src="{{$array['statuses'][$i]['entities']['media'][0]['media_url']}}" alt="" class="img-responsive"/>
</div>
@endfor
RESULT
Error Messages:
Undefined index: media
At twitter API v1.1 media entities is disappear when people not post picture, so when i trying to get json data with looping concept and media_url object is undefined, and than i result is error message. sorry my english so bad, i'm still newbie in php and api.
Your code is fine and you're saying that sometimes there is no ['media'] property, so you want to use something like this:
@for ($i = 0; $i < $tes; $i++)
@if(isset($array['statuses'][$i]['entities']['media']))
<div class="col-md-4">
<img src="{{$array['statuses'][$i]['entities']['media'][0]['media_url']}}" alt="" class="img-responsive"/>
</div>
@endif
@endfor
So, when there is a picture in a $array
, your view will generate HTML to display it. If you don't have, it will be skipped.