AppDividend
Latest Code Tutorials

Laravel Linkedin Login Tutorial

246

Laravel Linkedin Login Tutorial is the topic, we will discuss today. In this tutorial, we can use laravel latest version 5.6.15. I am going explain to you how to Login users with Linkedin and save them into your database using Laravel. Laravel provides us Socialite package that helps with social authentication.

Laravel Linkedin Login Tutorial

First, we install Laravel Project.

Step 1: Configure Laravel Project

composer create-project --prefer-dist laravel/laravel laravellinkedinlogin

Step 2: Setup a MySQL database

Instantly, configure the database in the .env file.

//.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravellinkedin
DB_USERNAME=root
DB_PASSWORD=

Next, migrate two tables provided by Laravel 5.6 Move to your terminal and hit the following command.

php artisan migrate

It will produce two tables in your database.

  1. users
  2. password_resets  

In users table, we can add one field called linkedin_id.

//create_users_table

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('linkedin_id');
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Immediately, migrate the table by the following command.

Related Posts
1 of 26
php artisan migrate

Step 3: Create a Laravel Authentication

Laravel provides us basic authentication. Laravel 5.6 makes implementing authentication very simple.We only want to fire one command in our terminal.

php artisan make:auth

Now, if we change the routes >> web.php file then there is one added route, and to our view is configured automatically.

//web.php

Auth::routes();

Step 4: Download the laravel/socialite package for laravel linkedin integration

The socialite is a package that makes building authentication with popular social networks simple. So we are using this Laravel 5.6 specific package.

composer require laravel/socialite

Find the providers in config >> app.php file and register the SocialiteServiceProvider.

'providers' => [
        // ...
        Laravel\Socialite\SocialiteServiceProvider::class,
    ]

Locate the aliases in config >> app.php file and register the aliases.

'aliases' => [
        // ...
        'Socialite' => Laravel\Socialite\Facades\Socialite::class,
    ]

Step 5: Create Linkedin App To Get Tokens

Go to the Linkedin’s developers portal by following URL: https://www.linkedin.com/developer/apps

Login via your Linkedin account. You will see something like this.

Laravel 5.6 Linkedin Login Tutorial

 

Soon you have to click on Create Application and fill form details and create a new application.  After generated application you can see the following slide:

Laravel Socialite Login Tutorial

In above image, you can see Client ID and Client Secret, which we need in our Laravel Application.

Now, grab both of them and shift to your editor.

Drive to the config  >>  services.php file and put one extra services array by the following code.

//services.php

'linkedin' => [
        'client_id' => 'xxxx',
        'client_secret' => 'xxxx',
        'redirect' => 'http://localhost:8000/callback'],

Step 6: Generate a controller

Now, we need to create one controller, which handles the Linkedin Authentication routes.

php artisan make:controller SocialAuthLinkedinController

We must implement two methods in this controller, which are following.

1)redirect():  Redirect our users to the Linkedin.

2) callback():  Handle callback from Linkedin.

//SocialAuthLinkedinController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Socialite;
use Auth;
use Exception;



class SocialAuthLinkedinController extends Controller
{
    public function redirect()
    {
        return Socialite::driver('linkedin')->redirect();
    }


    public function callback()
    {
        try {
            $linkdinUser = Socialite::driver('linkedin')->user();
            $existUser = User::where('email',$linkdinUser->email)->first();
            if($existUser) {
                Auth::loginUsingId($existUser->id);
            }
            else {
                $user = new User;
                $user->name = $linkdinUser->name;
                $user->email = $linkdinUser->email;
                $user->linkedin_id = $linkdinUser->id;
                $user->password = md5(rand(1,10000));
                $user->save();
                Auth::loginUsingId($user->id);
            }
            return redirect()->to('/home');
        } 
        catch (Exception $e) {
            return 'error';
        }
    }
}

Next step is moving to the routes >> web.php file and register the routes.

//web.php

Route::get('linkedin', function () {
    return view('loginlinkedin');
});
Auth::routes();

Route::get('/redirect', 'SocialAuthLinkedinController@redirect');
Route::get('/callback', 'SocialAuthLinkedinController@callback');

Route::get('/home', 'HomeController@index')->name('home');

Step 7: Create LinkedinLogin view file

Create a file in the resources  >>  views  >>  loginlinkedin.blade.php and set the following code in it.

//loginlinkedin.blade.php

<html lang="en">
<head>
    <title>Laravel Linkedin Login</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
</head>
<body>
<div class="container">
      <h2>Laravel Linkedin Login</h2><br/>
      <form method="post" action="{{ url('/login') }}">
        @csrf
        <div class="row">
        <div class="col-md-4"></div>        
            <div class="form-group col-md-4">
              <label for="Email">Email:</label>
              <input type="text" class="form-control" name="email">
            </div>
          </div>
        <div class="row">
        <div class="col-md-4"></div>        
            <div class="form-group col-md-4">
              <label for="Password">Password:</label>
              <input type="password" class="form-control" name="password">
            </div>
          </div>
          <div class="row">
          <div class="col-md-4"></div>          
            <div class="form-group col-md-4">
            <input type="checkbox" name="remember"> Remember Me
            </div>
          </div>
          <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
            <a href="{{ url('/redirect') }}" class="btn btn-primary">Login With Linkedin</a>
            <button type="submit" class="btn btn-success">Login</button>
            </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>          
            <div class="form-group col-md-4">
            <a class="btn btn-link" href="{{ url('/password/reset') }}">Forgot Your Password?</a>
            </div>
          </div>
      </form>
    </div>
</body>
</html>

Now, if you have not begun the server, then start the server and go the following URL

http://localhost:8000/linkedin

 

Login with Linkedin Laravel

Finally, Our Laravel Linkedin Login Tutorial is over. Thank You.

Leave A Reply

Your email address will not be published.