Integrating Facebook Login into Laravel application

In this tutorial, we are going to create a Facebook login feature for Laravel 5 using Socialite package.

Note: In order to complete this tutorial, you should have a basic understanding of Laravel Framework.

Step 1: Installation and Configuration:

a) To get started, navigate to your Laravel installation and type the following command to install socialite

composer require laravel/socialite

Recommended: How to Install composer on Windows with XAMPP

b) In the next step, open to config/app.php and add the code given below to providers array.

socialite-facade

socialite-facade

c) Also, add the Socialite’s facade to aliases.

socialite

socialite

Socialite is now registered within your application.

Step 2: Create a Facebook App:

a) Visit Facebook Developer Page and create a new app.

Recommended: http://coffeecupweb.com/how-to-get-an-app-id-and-secret-key-from-facebook/

b) After creating the app, navigate to App > Settings > Add platform.

c) In Select Platform Popup, select Website. 

d) This will create a new Website Section on settings page. Within Website section look for Site URL textbox. In this textbox enter your websites URL.

e) And, copy the App ID and App Secret for your application.

Step 3: Add Facebook App ID and Secret to Your Application:

Navigate to app\services.php and the following details,

'facebook' => [
    'client_id' => 'facebook_app_id',
    'client_secret' => 'facebook_app_secret',
    'redirect' => 'redirect_url',
 ],

redirect is the URL where user will be redirected after authentication.

Step 4: Setup routes and controller methods

We are going to create to routes in our application, one for redirecting user to authentication page and second will be the callback where user will be redirected after authentication.

Define routes for laravel socialite

Define routes for laravel socialite

Note: Add these routes inside web middleware group in routes file.

Next, we need to create redirectToFacebook and handleCallback methods inside Auth\AuthController.php file.

AuthController Socialite

AuthController Socialite

Make sure, you have added socialite class reference at the top of the controller.

use Socialite;

Once you have user instance inside handleCallback, you can grab the details available within the instance and can save it to your database.

That’s it. In case you have any queries, please let me know.

0 Comments

Leave a Comment.