Create Laravel 8 Social Login with LinkedIn using Socialite

Laravel 8 login with the Linkedin tutorial; Social login is a great way to access a third-party website, and there are various social media platforms through which you can login without putting in the extra effort. This post will share with you exorbitantly facile methods on how to create a Laravel 8 LinkedIn social login system using the Laravel Socialite package from scratch.

Login with LinkedIn in Laravel 8 will require a Socialite library; the Socialite package allows you to develop tons of social login systems. Not just LinkedIn, but you can also go forward with other OAuth providers, such as Facebook, Twitter, GitHub, and many more.

To integrate LinkedIn social login in laravel, you need to set up a laravel environment. For that, you need a composer package and socialite package. Right after that, you have to make the database and laravel connection.

To enhance development speed, we will use Laravel JetStream and Livewire packages, and we will install those in subsequent steps. Also, you will require a LinkedIn client id and secret key; hence we will also teach you how gradually get the linkedin secret keys using the linkedin developers account.

Laravel 8 LinkedIn Social Login Example

  • Step 1: Install Laravel App
  • Step 2: Add Database Credentials
  • Step 3: Add Jetstream Package
  • Step 4: Install Socialite Pacakage
  • Step 5: Add Social Login Field in Current Table
  • Step 6: Create and Add Linkedin Client ID and Secret
  • Step 7: Create Controller
  • Step 8: Add Routes
  • Step 9: Set Up Login View
  • Step 10: Run Laravel Application

Install Laravel App

We assume you have already Installed the composer PHP dependency manager, next run command to create the laravel project:

composer create-project laravel/laravel --prefer-dist demo-app

Add Database Credentials

To make the connect laravel app to database, add database credentials in .env file:

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

Add Jetstream Package

Further, make sure to install Jetstream and laravel livewire packages in laravel app:

composer require laravel/jetstream

php artisan jetstream:install livewire

npm install

npm run dev

After installing given above libraries and packages, make sure to migrate User table into the database:

php artisan migrate

Install Socialite Pacakage

Next, you have to install the socialite library, hence open console and execute the following command:

composer require laravel/socialite

Additionally, inject socialite classes in providers and aliases arrays within the config/app.php file:

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

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

Add Social Login Field in Current Table

In the coming step, you need to create a new field in the current table into the database for handling social login, consequently execute command to create a new migration file:

php artisan make:migration add_social_login_field

Open and update social login values in database/migration/add_social_login_field.php file as given below:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddSocialLoginField extends Migration
{
   /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('socialite_id')->nullable();
            $table->string('socialite_type')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('socialite_id');
           $table->dropColumn('socialite_type');
         });
    } 
}

Then, also update the new properties in app/Models/User.php file:

<?php

namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'socialite_id',
        'socialite_type'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}

After adding social login properties in migration file, then execute the following command to insert the new properties into the database:

php artisan migrate

Create and Add Linkedin Client ID and Secret

Further, we need to create a LinkedIn client id and secret keys, and it will establish the connection between laravel and linkedin.

For that, we must have a linkedin account, head towards the linkedin developers platform, and signin using th linkedin credentials.

To get client id and secret, make sure to click on Create app:

create Linkedin developers account

On this page, you have to add the app name and make sure to add LinkedIn page and the app logo, then accept the legal agreement and click on create app button:

Create an linkedin app

Now, you have entered into the LinkedIn app page, next click on Auth tab and inside the authentication keys locus copy your client id and secret:

linkedin authentication keys

You have to include the authentication keys inside the open the config/services.php file:

return [
    'linkedin' => [
        'client_id' => 'xxxxxxxxxxxxx',
        'client_secret' => 'xxxxxxxxxxxx',
        'redirect' => 'http://127.0.0.1:8000/auth/callback/linkedin',
    ],
]

Create Controller

Create a controller which helps you define the program logic for managing linkedin social login; run the suggested command:

php artisan make:controller LinkedinAuthController

Open and insert the following code in app/Http/Controllers/LinkedinAuthController.php file:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Auth;
use Exception;
use Socialite;
use App\Models\User;

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

    public function cbLinkedin()
    {
        try {
     
            $user = Socialite::driver('linkedin')->user();
      
            $user = User::where('socialite_id', $user->id)->first();
      
            if($user){
      
                Auth::login($user);
     
                return redirect('/admin');
      
            }else{
                $user = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'socialite_id' => $user->id,
                    'socialite_type' => 'linkedin',
                    'password' => encrypt('user555555999')
                ]);
     
                Auth::login($user);
      
                return redirect('/admin');
            }
     
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Add Routes

Open routes/web.php file, import Linkedin AuthController at the beginning, then create two routes to handle social login:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LinkedinAuthController;

 
Route::get('auth/linkedin', [LinkedinAuthController::class, 'loginWithLinkedIn']);
Route::get('auth/callback/linkedin', [LinkedinAuthController::class, 'cbLinkedin']);

Set Up Login View

At last create a Login with Linkedin button, add some inline styling into it and add the given below code in views/auth/login.blade.php file:

<x-guest-layout>
    <x-jet-authentication-card>
        <x-slot name="logo">
            <x-jet-authentication-card-logo />
        </x-slot>

        <x-jet-validation-errors class="mb-4" />

        @if (session('status'))
        <div class="mb-4 font-medium text-sm text-green-600">
            {{ session('status') }}
        </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf
            <div class="flex items-center justify-end mt-3">
                <a class="btn" href="{{ url('auth/linkedin') }}"
                    style="background: #0475B0; color: #ffffff; width: 100%; padding: 12px; text-align: center; border-radius:4px; display: block; ">
                    Login with Linkedin
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Run Laravel Application

Lastly, run the command in the terminal to start the app:

php artisan serve

Add the url in the browser to run the project:

http://127.0.0.1:8000/login

implement login with LinkedIn in laravel

Conclusion

Finally, you have learned how to implement login with LinkedIn in the laravel app using the socialite package. We assume you have gone through every step and develop the laravel social login system.