The LinkedIn tutorial for Laravel social login or signin; In this detailed example, we'll show you how to create a LinkedIn login in a Laravel application from scratch using the Laravel socialite, Livewire, and Jetstream libraries.

The key issue that we will cover with the socialite package in Laravel is Linkedin social login. With its OAuth provider techniques, the Socialite plugin makes the social login procedure simple.

Not only is Linkedin Login or signin integration simple in Laravel. Other social platforms, on the other hand, may be implemented far more rapidly and easily.

You must create or generate the linkedin client id and secret in order to integrate Linkedin social login in Laravel. You must have a linkedin account and be logged in with your linkedin credentials.

You may go to the LinkedIn developer console and get the client id and secret keys, which you can then inject into the Laravel project to make the two platforms work together.

Laravel 9 Social Login with LinkedIn Example

Table of Content

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

1. Set Up Laravel Project

You must first install the composer package on your machine before running the command to install the laravel app:

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

2. Make Database Connection

Then, in the .env file, enter the database information:

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

3. Install Jetstream Library

The final step is to install the JetStream package in Laravel, which provides you with pre-defined authentication templates that are powered by Tailwind CSS:

composer require laravel/jetstream

Execute the following command to generate ready-to-use authentication templates:

php artisan jetstream:install livewire

Next, run the following command to install the necessary npm packages:

npm install
npm run dev

Then, with the following command, run migration:

php artisan migrate

4. Configure Socialite Pacakage

To add the socialite package to Laravel, switch to the command line tool and run the following command:

composer require laravel/socialite

As seen below, register socialite classes in the config/app.php configuration file:

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

5. Add and Migrate Linkedin Property in Users Table

To manage linkedin sign-in, we need to add a new field to the existing user table, so first create the migration file:

php artisan make:migration add_social_auth_id_field

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

<?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, enter the app/Models/User.php file and add the following new social auth fields:

<?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, use the following command to add new values to the user table:

php artisan migrate

6. Add Linkedin Client ID and Secret

Let's get started by going to the LinkedIn developers account and creating a client id and secret:

Then, select Create Application from the drop-down menu:

You must add an app name, your LinkedIn page name, or a url to the Make an app page; if you don't have one, please create one. Finally, upload the app logo and proceed to the following step:

Your LinkedIn app has been built; you will see the various sections, but you must first open the Auth tab. You must copy the Authentication keys to add to the Laravel app in the Application credentials area.

We've created the LinkedIn app and obtained the client id and secret; now open the config/services.php file and enter the linkedin credentials as follows:

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

7. Prepare Controller

Using the artisan command, create a new controller:

php artisan make:controller LinkedinController

Then, under app/Http/Controllers/LinkedinController.php, add the following code:

<?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());
        }
    }
}

8. Define Routes

Also, in the routes/web.php file, define a pair of routes to handle authentication 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']);

9. Set Up Login View

Finally, open the views/auth/login.blade.php ready-made template, build a login with a linkedin button, and add the route that allows you to make 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>

10. Start Laravel App

In this final stage, we'll use the PHP artisan command to invoke the Laravel development server, then go to the console and enter the following command:

php artisan serve

As a result, test the app using the following url:

http://127.0.0.1:8000/login

The LinkedIn login tutorial for Laravel is now complete.

We learned how to use the JetStream library to construct ready-made auth templates as well as how to integrate login with LinkedIn in the Laravel app using the Laravel socialite's OAuth provider.

I hope you will like the content and it will help you to learn Laravel 9 Socialite Login with LinkedIn Tutorial Example
If you like this content, do share.


Recommended Posts

View All

Laravel where and orWhere Condition Example


how to use where and orwhere condition in laravel 8, laravel 8 where and orwhere condition, where and orwhere laravel 8 example, orwhere and where in...

Laravel whereMonth and whereYear Example


laravel whereMonth and whereYear example, whereMonth, whereYear, where condition in laravel 8, date function in laravel 8, whereMonth and whereYear in...

Laravel One to Many Eloquent Relationship


laravel one to many relationship example, laravel one to many sync, one to many relationship laravel 5.6, one to many relationship laravel model

Laravel – Where Condition with Two Columns Example


laravel where with two column example, two column where laravel , table column condition in laravel , laravel where column equals column example

Laravel 9 GEO Chart Example using LavaCharts


Learn how to create interactive GEO charts with Laravel 9 and LavaCharts. Visualize your data on maps and improve data analysis. Check it out now!