Skip to content

Instantly share code, notes, and snippets.

@jrnk
Created July 1, 2016 09:21
Show Gist options
  • Save jrnk/02a5a1e2a5338e24e69a232e16f3f1ec to your computer and use it in GitHub Desktop.
Save jrnk/02a5a1e2a5338e24e69a232e16f3f1ec to your computer and use it in GitHub Desktop.
Laravel & Instagram get latest images and cache
<?php
use Cache;
use GuzzleHttp\Client;
// set ENV variables: INSTAGRAM_USERNAME and optional INSTAGRAM_CACHE_TIME (in minutes, default = 60)
class InstagramGateway
{
public function getLatestPhotos($maxNumber = 4)
{
if (Cache::has('latest_instagram_photos')) {
$ig_photos = Cache::get('latest_instagram_photos');
} else {
try {
// cache instagram photos
$client = new Client();
$ig_endpoint = 'https://www.instagram.com/' . env('INSTAGRAM_USERNAME', 'shrt') . '/media';
$ig_response = $client->request('GET', $ig_endpoint);
$ig_data = json_decode($ig_response->getBody(), true);
$ig_photos = [];
foreach ($ig_data['items'] as $item) {
$ig_photos[] = [
'url' => $item['images']['standard_resolution']['url'],
];
if (count($ig_photos) == $maxNumber) {
break;
}
}
Cache::put('latest_instagram_photos', $ig_photos, env('INSTAGRAM_CACHE_TIME', 60));
} catch (Exception $e) {
$ig_photos = [];
}
}
return $ig_photos;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment