Integrating Instagram API in Laravel 5.6

In this tutorial, i’ll show you how to integrate Instagram API in Laravel App. We won’t be using any Instagram PHP wrapper library. Instead, we’ll use socialiteproviders/instagram provider to retrieve an access token from Instagram OAuth service and use it to make calls to Instagram API  with guzzlehttp/guzzle client.

Getting Started

After creating a new project, run php artisan preset bootstrap to remove default VueJs scaffolding. Install Laravel Socialite, Instagram Socialite provider, and GuzzleHttp package.

Instagram Socialite Provider Configuration

After installation, add \SocialiteProviders\Manager\ServiceProvider::class to service providers array in config/app.php  file.

Now edit app/Providers/EventServiceProvider and add SocialiteWasCalled event to your listen[] array in app/Providers/EventServiceProvider .

Now add Instagram config to config/service.php  array.

Registering a new Instagram Client

Register a new Instagram client. Fill in the details. Make sure your URI must match  env('INSTAGRAM_REDIRECT_URI').  User will be redirected back to this URI after authorization.

After registration, your app will show on the dashboard. Click manage and copy client id and secret. Edit .env file and add these credentials to it.

Generate Authentication Scaffolding

Run php artisan make:auth  to generate default authentication scaffolding. We’ll authenticate users with conventional form based authentication. After authentication, we’ll ask them to authorize with Instagram OAuth. We’re doing this because Instagram doesn’t provide an email address. We’ll create a separate table for storing user’s Instagram access tokens and retrieve them with HasOne relation.

Migrations

We are creating two tables, users and instagram. Registered users will be stored on users table and their access token on instagram  table along with their user_id. CreateUsersTable migration comes pre-created with laravel app. Run

php artisan make:migration CreateInstagramTable --create=instagram

to create a new migration and add these columns to it.

We’re creating user_id column and referencing it to id column on users table. We also specified an onDelete action when user record will be deleted. After adding your database credentials to .env file, run php artisan migrate  to create database tables.

Models

Create an Instagram model with php artisan make:model Instagram

Modify your existing User model and add a method to retrieve an associated record from instagram table with One to One relation.

Now we’ll be able to verify if a user has an access token record on instagram table with Auth::user()->instagram.

Routes

We’ve moved all routes to an authenticated route group. After authentication, user will be redirected to /  URI. /instagram route will redirect users to Instagram OAuth service and /instagram/callback will receive user Object after authorization.

Instagram API Class

Create Classes folder under app directory. Now create an InstagramAPI class in it. We’ll write our API logic in this class and then bind it to the service container. We’ll also create a Facade and Alias to call its methods statically.

In the constructor, we’re creating an instance of GuzzleHttp Client by passing a base URI to it. Then we have a setAccessToken() method that we’ll statically call from a middleware to set user’s access token. We’ll call  getUser() , getPosts()  and getTagPosts() method to retrieve data from API in controllers.

Service Provider

We’re creating a service provider to bind InstagramAPI class to the service container. Run php artisan make:provider InstagramServiceProvider to create a new service provider and add this code to it.

Now add your service provider to config/app.php providers[] array.

Facade

To use InstagramAPI class methods statically, we’ll create a facade for it. Create Facade folder in your app directory and create an InstagramFacade.php  file under it. Add this code to it.

I’ll be using this Facade in controllers. If you want to, you can create an Alias for it. Add this line to config/app.php  aliases[]  array.

'Instagram' => App\Facades\Instagram::class

Middleware

We need to call setAccessToken() method to set user access token before using any of InstagramAPI methods in our controllers. Since sessions data is not available in service providers, the only way to do it is to call it in a controller’s constructor or middleware. Run php artisan make:middleware InstagramAPIMiddleware to create a new middleware and add this code to it.

Also, add this middleware to app\Http\Kernal.php routerMiddleware[]  array.

Now apply this middleware to authenticated route group in app/routes/web.php  file.

Controllers

In our InstagramController, we’ve two methods.

redirectToInstagramProvider() will redirect user to OAuth server and handleProviderInstagramCallback() method receives a user object after user authorizes. We’re creating a new related instagram model record if it doesn’t exist. The new record will have an access token and user_id of the authenticated user. If a record already exists, we simply update the access token.

In our AppController, we’re using Instagram  Facade to retreieve user info, posts and tagged posts and then passing to our index.blade.php php view.

Views

In our index.blade.php view, We’ll render a button instead of content if the authenticated user doesn’t have a record on instagram table. If a user has already authorized Instagram access, we’ll render their profile info along with posts.

Exception Handling

To handle exceptions thrown by GuzzleHttp, update  app\Exceptions\Handlers.php  render() method.

You can render custom response for errors raised by GuzzleHttp. You can raise your own custom errors and handle them here.

Instagram made some serious changes to their API after Facebook’s privacy issues. Many API endpoints for posting media and comments are deprecated. Read more about it here. I’ve set up an example repository for you. If you’ve any issues or errors, please comment. I’ll try to help you with it.

Share this post

23 thoughts on “Integrating Instagram API in Laravel 5.6”

  1. Hi there.
    I’ve cloned your repository updated and after instagram login, when the user redirects to app i get this error “An error occurred when making request to InstagramAPI”
    Any ideas? Thanks

      1. I’ve tested it on both Linux and Windows and it seems to work without any issues. I’ve recorded a video.

        The only reason I can think of why you might be getting this error is invalid or empty env variables. Try dumping env('INSTAGRAM_KEY') or env('INSTAGRAM_SECRET') from anywhere within your app to see if they are set up properly. There’s this issue where env variables sometimes return null values. Try after running php artisan config:clear and php artisan cache:clear and see it it works.

  2. Thanks for this. I got it up and running. I think the issue cited by others might be that you’ve specified:

    php artisan make:middleware InstagramMiddleware

    But the class name is actually InstagramAPIMiddleware.

  3. Hi everyone ! I have a little issue creating the middleware, I got this error:

    $ php artisan make:middleware InstagramAPIMiddleware
    In ProviderRepository.php line 208:
    Class ‘App\Providers\InstagramSerivceProvider’ not found

    I try this composer’s commands but it still not working:

    composer update –no-scripts
    composer dump-autoload -o

    .. also when run any artisan query get that error!

  4. Hello !
    In the provider section you call your provider “InstagramSerivceProvider” instead of “InstagramServiceProvider”.

    Good guide btw !

  5. Hello i got this issue after click the button authenticate with instagram
    Call to undefined method SocialiteProviders\Instagram\Provider::getAccessTokenResponse()

    how can i solve this?

    thankyou 🙂

  6. this is not working my computer.. 🙁

    Class ‘App\Facades\Instagram’ not found

    what is it..?

    my code is all same blog

  7. ‘providers’ => [
    […] // other providers
    \SocialiteProviders\Manager\ServiceProvider::class,
    \App\Providers\InstagramSerivceProvider::class, <——-
    ],
    serivce is mistake right is service

  8. Hey all, can you answer a quick question in regards to this tutorial. What happens with the application when the instagram access token expires?

  9. When I click ‘authenticate with Instagram’ this error occurs:
    {“error_type”: “OAuthException”, “code”: 400, “error_message”: “Invalid scope field(s): public_content”}

    Could I get a fix on this, thanks

  10. Hello
    I downloaded your project from github and now I am getting this error whenever I click on authenticate with instagram button. Please help it’s urgent.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.