You can create a LinkedIn login for your web application using the socialite package in Laravel 8. LinkedIn provides the OAuth login for user authentication. The entire process is handled by the LinkedIn app. You will require to create an app in the LinkedIn Developer Console. The login with LinkedIn will manage by this app. It will ask you to allow permission. Once you have done, you will be able to login to your web application by LinkedIn account. I already shared tutorials on Login with Google and Login with Facebook in Laravel using socialite. Today, in this post, I will be sharing with you the complete steps for creating the Login with Linkedin functionality. So, let’s begin by creating a new project in Laravel 8.
Prerequisites
Before moving to this example, please make sure you are ready to create a Laravel 8 application. If not then please configure the below tools in your system.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create a Laravel Project for LinkedIn Login
For creating the Laravel 8 project, I will be using the composer. Hence, I have already installed it in my system. So, open the terminal and create a new project by hitting the below command.
composer create-project --prefer-dist laravel/laravel laravel-socialite
The project installation is started. So, when it is ready let’s configure the database.
How to Schedule Tasks with Cron Job in Laravel 8
Create and Configure a Database For Laravel Project
In this step, we will create a database in MySQL. For this project, I am using MySQL for the database management. So, create a new database first.
CREATE DATABASE laravel_socialite;
After creating the database, just come back to the project. Open it into the editor and let’s configure the database credentials. To connect the database, just open the .env file and replace the DB credentials as showing below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_socialite
DB_USERNAME=root
DB_PASSWORD=root
In the next step, we will be installing the Laravel UI Auth package for the authentication system. You can install Jetstream with Livewire or Jetstream with Inertia js. It is up to you how you will manage the authentication.
Install UI Auth in Laravel 8 For LinkedIn Login
Inside the project folder, just install the UI auth package for the Laravel default auth system.
composer require laravel/ui
The above package will help to use the Login, Register, Logout and session functionality. This is a complete authentication by default through a package.
This package will add the necessary dependencies for the auth scaffolding. In the next step, we will have to install the Auth Scaffolding.
Import and Export CSV and Excel File in Laravel 8
Install Vue Auth Scaffolding in Laravel 8
The Auth Scaffolding will provide the authentication functionality inside the project. So, install it using the below command.
php artisan ui vue --auth
This package will ask to install the npm for the UI auth. Actually, it will generate the necessary CSS and js for the UI. Hence, install it using the below command.
npm install && npm run dev
After the compiling it will build a CSS and js file for the front end UI.
Now, if you will run the Laravel application, you will see the default homepage has the Login and Register option.
Now, in the next step, we will install socialite package in our project.
How to Generate PDF File in Laravel 8 Using DOM PDF
Install Socialite package in Laravel 8
For the implementation of LinkedIn login in Laravael, you will require to install the socialite package. Hence, install it using the below command.
composer require laravel/socialite
Once it is installed, we will register it into the providers array. Also, will create it’s alias.
Add Provider and Alias for Socialite Package
To register the provider for the socialite package, just go to the config/app.php. Now, inside the providers array add the provider. Simiarly, add the alias in the aliases array.
'providers' => [
…
…
…
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
…
…
…
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
Now, we can use the alias in our controller to proceed with the LinkedIn login using socialite.
RESTful APIs For Todo App Using Passport Auth in Laravel 8
Get Client Id and Client Secret From LinkedIn App
But, before moving to the main functionality, it’s time to get the client id and client secret from the LinkedIn developer app. So, firstly, create an app in LinkedIn.
Fill the required details to create app. In the next step, it will ask you to set the callback URL. So, once you completed the steps, you will get the client id and client secret for this app.
How to Implement Invisible reCAPTCHA in Laravel 8
Configure Client Id and Secret in Laravel
To configure the LinkedIn app client id and client secret, you will have to open the config/services.php file.
return [
…
…
…
'linkedin' => [
'client_id' => 'LINKEDIN_APP_CLIENT_ID',
'client_secret' => 'LINKEDIN_CLIENT_SECRET',
'redirect' => 'http://localhost:8000/auth/linkedin-callback',
],
];
Now, it is done on the configuration side. In the next step, we will have to add one field in the users migration table. Actually, after the login, we will store the logged user id in the users table. Hence, we required to add it in the migration and fillable data.
Add Column in Migration and Fillable Data
You can achieve the column adding in two ways. Firstly, you can create a new migration file for the same table. Secondly, you can add a new column to the existing migration table. Here, I have added the column in the existing migration table of users.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->string('linkedin_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Now, we have to add this column inside the fillable array of the user model. So, let’s do that.
<?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;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'linkedin_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
At last you have to migrate the table. So, hit the below command to migrate the tables.
php artisan migrate
After the migration, you will have to create a controller to put some functionality there.
Create Authentication in Laravel 8 Using Laravel Breeze
Create Controller For LinkedIn Login
For creating the controller for the managing the socialite authentication, hit the below command.
php artisan make:controller SocialiteAuthController
After creating the controller, just put the below code inside it.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Socialite;
use Illuminate\Support\Facades\Auth;
use Exception;
class SocialiteAuthController extends Controller
{
public function linkedinRedirect()
{
return Socialite::driver('linkedin')->redirect();
}
/**
* Facebook login authentication
*
* @return void
*/
public function loginWithLinkedIn()
{
try {
$linkedinUser = Socialite::driver('linkedin')->user();
$user = User::where('linkedin_id', $linkedinUser->id)->first();
if($user){
Auth::login($user);
return redirect('/home');
}
else{
$createUser = User::create([
'name' => $linkedinUser->name,
'email' => $linkedinUser->email,
'linkedin_id' => $linkedinUser->id,
'password' => encrypt('test@123')
]);
Auth::login($createUser);
return redirect('/home');
}
} catch (Exception $exception) {
dd($exception->getMessage());
}
}
}
For the above functions, we have to create some routes.
Create Routes For Socialite LinkedIn Login
Open the routes/web.php file and put the below routes there.
Route::get('linkedin', [SocialiteAuthController::class, 'linkedinRedirect'])->name('auth/linkedin');
Route::get('/auth/linkedin-callback', [SocialiteAuthController::class, 'loginWithLinkedIn']);
At last, we have to put a button inside the login.blade.php file for redirecting to the LinkedIn.
User Authentication in Laravel 8 Using UI Auth Package
Create a Button for LinkedIn Login
You will have to put a button for redirecting it to the LinkedIn authorization login. Hence, in the below code, I have added a button for the LinkedIn Login in the login.blade.php file.
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
@csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-secondary">
{{ __('Login') }}
</button>
<a href="{{ route('auth/linkedin') }}" class="btn btn-primary">
{{ __('Login with LinkedIn') }}
</a>
</div>
<div class="col-md-8 offset-md-4">
@if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
@endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
Now, you are done. Just check the result by running the application.
Result of LinkedIn Login in Laravel 8
Check the result in the browser. After clicking on the Login button in the homepage, you will have the login page.
In the login page, you will see the Login with LinkedIn button as showing below.
After clicking on the Login with LinkedIn button, it will redirect you to the LinkedIn OAuth login. After the successful login, it will return you to the callback URL that we have already set in the callback.
That’s all for this post on LinkedIn Login in Laravel 8.
Conclusion
We have implemented successfully the functionality of LinkedIn login in Laravel 8. The overall functionality is dependent on the socialite package. The socialite package allows us to create the authorization between our application and the social platform authentication. I hope this tutorial will be helpful for you. If you stuck anywhere in this post then don’t forget to ask it through commenting in the comment section.
Leave a Reply