Laravel 10 Socialite Login with LinkedIn Tutorial Example

Last Updated on by in Laravel

Laravel social login or signin with the LinkedIn tutorial; In this extensive example, we will show how to implement login with Linkedin in laravel application with the help of laravel socialite, Livewire and Jetstream libraries from scratch.

Laravel LinkedIn social login is the primary topic which we will cover using the socialite package. Socialite plugin makes the social login process smooth with its OAuth provider methods.

Not just Linkedin Login or signin integration in laravel is easy. Still, also you can implement other social platforms immensely quickly and comfortably.

The implement Linkedin social login in laravel, you have to create or generate the LinkedIn client id and secret. You need to have the Linkedin account and using the LinkedIn credentials.

You can access the Linkedin developer console; from there, you can grab the client id and secret keys and inject them into the laravel app to make the consensus between laravel and Linkedin platforms.

Laravel 10 Social Login with LinkedIn Example

  • Step 1: Set Up Laravel Project
  • Step 2: Make Database Connection
  • Step 3: Install Jetstream Library
  • Step 4: Configure Socialite Pacakage
  • Step 5: Add and Migrate Linkedin Property in Users Table
  • Step 6: Add Linkedin Client ID and Secret
  • Step 7: Prepare Controller
  • Step 8: Define Routes
  • Step 9: Set Up Login View
  • Step 10: Start Laravel App

Set Up Laravel Project

First, you have to install composer package in your system, then you can run the command to install the laravel app:

composer create-project laravel/laravel --prefer-dist laravel-linkedin-login-example

Make Database Connection

Next, add the database details in .env file:

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

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Install Jetstream Library

In the third step, you have to install JetStream package in laravel, it gives you predefined authentication templates powered by Tailwind CSS:

composer require laravel/jetstream

Further, execute command to generate ready made auth templates:

php artisan jetstream:install livewire

Next, use command to install required npm packages:

npm install
npm run dev

After that, run migration with following command:

php artisan migrate

Configure Socialite Pacakage

Move to command line tool, and use command to add socialite package in laravel:

composer require laravel/socialite

Register socialite classes in config/app.php configuration file as suggested below:

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

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

Add and Migrate Linkedin Property in Users Table

To manage the signin with linkedin, we have to insert the new field in the existing user table, hence first generate the migration file:

php artisan make:migration add_social_auth_id_field

Thereafter add the new table values in the database/migration/add_social_auth_id_field.php file:

<?php

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

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

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

Next, open app/Models/User.php file and add new social auth fields within the 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',
        'oauth_id',
        'oauth_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',
    ];
}

Finally, execute command to migrate new values into the user tabel:

php artisan migrate

Add Linkedin Client ID and Secret

Let us start creating client id and secret by visiting the Linkedin developers account:

Then, click on create application button:

Linkedin developers account

On the Create an app page, you have to add app name, your LinkedIn page name, or url; if you don’t have, please create lastly add the app logo and continue to next step:

Your linkedin app has been created; you will see the various tabs; however, you have to open the Auth tab. Here in the Application credentials section, you have to copy the Authentication keys to add to the laravel app.

We have created the linkedin app and got the client id and secret; in the subsequent step, open the config/services.php file and register the linkedin credentials as given below:

return [
    ...

    'linkedin' => [
        'client_id' => 'xxxxxxxxxxx',
        'client_secret' => 'xxxxxxxxxx',
        'redirect' => 'http://127.0.0.1:8000/auth/linkedin/callback',
    ],
]

Prepare Controller

Create a new controller using the artisan command:

php artisan make:controller LinkedinController

Then, add the below code in app/Http/Controllers/LinkedinController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

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

    public function linkedinCallback()
    {
        try {
     
            $user = Socialite::driver('linkedin')->user();
      
            $linkedinUser = User::where('oauth_id', $user->id)->first();
      
            if($linkedinUser){
      
                Auth::login($linkedinUser);
     
                return redirect('/dashboard');
      
            }else{
                $user = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'oauth_id' => $user->id,
                    'oauth_type' => 'linkedin',
                    'password' => encrypt('admin12345')
                ]);
     
                Auth::login($user);
      
                return redirect('/dashboard');
            }
     
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Define Routes

Furthermore, go to routes/web.php file and define the couple of routes to handle auth requests:

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
 
Route::get('auth/linkedin', [LinkedinController::class, 'linkedinRedirect']);
Route::get('auth/linkedin/callback', [LinkedinController::class, 'linkedinCallback']);

Set Up Login View

Ultimately, get inside the views/auth/login.blade.php ready-made template, create a login with linkedin button, add the route which allows making the login request:

<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>
                <x-jet-label for="email" value="{{ __('Email') }}" />
                <x-jet-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')"
                    required autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label for="password" value="{{ __('Password') }}" />
                <x-jet-input id="password" class="block mt-1 w-full" type="password" name="password" required
                    autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label for="remember_me" class="flex items-center">
                    <x-jet-checkbox id="remember_me" name="remember" />
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
                    {{ __('Forgot your password?') }}
                </a>
                @endif

                <x-jet-button class="ml-4">
                    {{ __('Log in') }}
                </x-jet-button>
            </div>

            {{-- Laravel Login with Linkedin --}}
            <div class="flex items-center justify-end mt-5">
                <a class="btn" href="{{ url('auth/linkedin') }}"
                    style="background: #0E62BC; color: #ffffff; padding: 10px; width: 100%; text-align: center; display: block; border-radius:3px;">
                    Login with Linkedin
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Start Laravel App

In this last step, we just have to evoke the laravel development server using the PHP artisan command, head over to the console, and run the following command:

php artisan serve

Consequently, use the suggested url to test the app:

http://127.0.0.1:8000/login

Laravel Socialite LinkedIn Login Example

Conclusion

The Laravel login with linkedin tutorial is over.

In this example, we discovered how to integrate login with Linkedin in the laravel app using the laravel socialite’s OAuth provider not only but also we learned to use JetStream library to create ready-made auth templates.