In this extensive tutorial, you will discover how to create a login with GitHub in the Laravel app, using the laravel socialite and Jetstream packages.
GitHub is a powerful platform for web developers; it makes software development organized with its version control and source code management mechanism.
In this GitHub social login example, we will show you how to easily integrate Login with GitHub in the Laravel app.
Socialite is a magical package offered by Laravel, and it provides spontaneous methods to authenticate with OAuth providers for Facebook, Twitter, LinkedIn, Google, GitHub, GitLab, and Bitbucket.
Laravel 9 Login with Github Integration Example
- Step 1: Set Up Laravel Project
- Step 2: Connect with Database
- Step 3: Install Jetstream Pacakage
- Step 4: Register Socialite Pacakage
- Step 5: Update GitHub Social Auth Values in Table
- Step 6: Create & Register Github Client ID and Secret
- Step 7: Add Routes
- Step 8: Create Controller
- Step 9: Implement Login with GitHub in Laravel
- Step 10: Test Laravel GitHub Login
Set Up Laravel Project
Begin with installing a fresh laravel app using composer tool:
composer create-project laravel/laravel --prefer-dist laravel-demo-app
Connect with Database
Add database name, username and password in .env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=
Install Jetstream Pacakage
Jetstream package in laravel gives pre-defined authentication templates, hence run recommended command to install:
composer require laravel/jetstream
Generate auth templates with below command:
php artisan jetstream:install livewire
Further, use command to install required dependencies:
npm install
Now you can use command to compile scripts in laravel:
npm run dev
Next, run migration with php artisan command:
php artisan migrate
Register Socialite Pacakage
In this step you have to install socialite package, so execute command and invoke the installation:
composer require laravel/socialite
Right after the package installation, go to config/app.php file and update providers and aliases arrays with socialite classes:
...
...
'providers' => [
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
...
...
Update GitHub Social Auth Values in Table
This step tells how to add GitHub social auth values in users table, not only but also how to update the existing users table:
Hence, execute the following command to create a fresh migration file:
php artisan make:migration add_github_id
Furthermore, open and update given below code in database/migration/add_github_id.php file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddGithubId extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function ($table) {
$table->string('git_id')->nullable();
$table->string('oauth_type')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function ($table) {
$table->dropColumn('git_id');
$table->dropColumn('oauth_type');
});
}
}
Open and add the new table values for GitHub login 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 HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'git_id',
'oauth_type',
];
/**
* 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',
];
}
Use the artisan command to run the migration:
php artisan migrate
Create & Register Github Client ID and Secret
In this step, you have to create a GitHub client id, and secret thereupon heads over to the GitHub site, create an account and access the GitHub developers page.
You have to create an OAuth app, so click on the green button:
Next, register a new OAuth application, hence provide the app name, homepage url, authorization callback url and click on the register application button:
Ideally, you can get the Client ID and Client secrets from the OAuth page, so copy both the credentials; we need these shortly.
Next, open the config/services.php file and add both id and secrets simultaneously within the services file:
return [
'github' => [
'client_id' => 'xxxxxxxxxxxxx',
'client_secret' => 'xxxxxxxxxxxx',
'redirect' => 'http://127.0.0.1:8000/github/auth/callback',
],
]
Add Routes
In the subsequent step, we have to create routes to handle Github social OAuth login in laravel, open routes/web.php file and update the provided code:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\GithubAuthController;
Route::get('github/auth', [GithubAuthController::class, 'githubAuth']);
Route::get('github/auth/callback', [GithubAuthController::class, 'callbackGithub']);
Create Controller
Further, open the console and execute command to generate a new controller:
php artisan make:controller GithubAuthController
You have to add the given below code in app/Http/Controllers/GithubAuthController.php file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Exception;
use Socialite;
use Auth;
class GithubAuthController extends Controller
{
public function githubAuth()
{
return Socialite::driver('github')->redirect();
}
public function callbackGithub()
{
try {
$user = Socialite::driver('github')->user();
$findUser = User::where('git_id', $user->id)->first();
if($findUser){
Auth::login($findUser);
return redirect('/home');
}else{
$user = User::create([
'name' => $user->name,
'email' => $user->email,
'git_id'=> $user->id,
'oauth_type'=> 'github_oauth',
'password' => encrypt('555555555555')
]);
Auth::login($user);
return redirect('/home');
}
} catch (Exception $e) {
dd($e->getMessage());
}
}
}
Implement Login with GitHub in Laravel
In this step, we have to create a simple button and pass the route which makes the request to Login with GitHub in Laravel, hence insert the following 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>
<x-jet-label value="{{ __('Email') }}" />
<x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required
autofocus />
</div>
<div class="mt-4">
<x-jet-label value="{{ __('Password') }}" />
<x-jet-input class="block mt-1 w-full" type="password" name="password" required
autocomplete="current-password" />
</div>
<div class="block mt-4">
<label class="flex items-center">
<input type="checkbox" class="form-checkbox" 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">
{{ __('Login') }}
</x-jet-button>
</div>
{{-- Laravel GitHub Login Example --}}
<div class="flex items-center justify-end mt-4">
<a class="btn" href="{{ url('github/auth') }}"
style="background: #313131; text-align: center; color: #ffffff; width: 100%; display: block; border-radius:4px; padding: 8px; ">
Login with GitHub
</a>
</div>
</form>
</x-jet-authentication-card>
</x-guest-layout>
Test Laravel GitHub Login
Run the application to checkout the feature we have just created:
php artisan serve
Open the app on the provided url:
http://127.0.0.1:8000/login
Summary
Ultimately, Laravel Github social login example is over.
In this tutorial, we understood how to build a login with GitHub in laravel with socialite library from scratch and update the Github login data into the database.