Laravel 11 Socialite Login with Github Account Example

By Hardik Savani September 4, 2024 Category : Laravel

In this article, we will learn laravel 11 login with github account using socialite composer package. we can use with laravel ui, laravel jetstream and laravel breaze for login with github account.

As we know, social media becomes more and more popular in the world. Everyone has a social account like Github, Gmail, Facebook, twitter etc. I think also most have github accounts. So if your application has login with social, then it becomes awesome. You get more people to connect with your website because most of the people do not want to fill out the sign-up or sign-in form. If they login with social, then it becomes awesome.

In this example, we will install the Socialite composer package for login with Github Account. Then we will install Laravel UI for Bootstrap authentication. After that, we will add a login with github button, allowing users to log in and register using their github account. So, let's follow the steps below:

laravel 11 login with github

Step for Login with Github Account in Laravel 11?

  • Step 1: Install Laravel 11
  • Step 2: Install Laravel UI
  • Step 3: Install Socialite
  • Step 4: Create Github App
  • Step 5: Add github_id Column
  • Step 6: Create Routes
  • Step 7: Create Controller
  • Step 8: Update Blade File
  • Run Laravel App

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install Laravel UI

Now, in this step, we need to use Composer command to install Laravel UI, so let's run the below command and install the below library.

composer require laravel/ui

Now, we need to create authentication using the below command. You can create basic login, register, and email verification. We will run the below commands to create Bootstrap auth scaffold:

php artisan ui bootstrap --auth

Now, let's node js package:

npm install

let's run package:

npm run build

Step 3: Install Socialite

In the first step, we will install the Socialite Package, which provides an API to connect with github accounts. So, first open your terminal and run the below command:

composer require laravel/socialite

Step 4: Create Github App

To create our Github app and receive the app credentials open the Github Developer Portal and sign up or log in.

To guide you through the steps listed above, I’ve included screenshots of the entire process below:

1. Create New OAuth App

2. Add Application details and Click on submit button

3. Copy Client ID and Secret from this screen and add on .env file.

Now you have to set app id, secret and call back URL in config file so open config/services.php and set id and secret this way:

config/services.php

return [
    ....

    'github' => [
        'client_id' => env('GITHUB_CLIENT_ID'),
        'client_secret' => env('GITHUB_CLIENT_SECRET'),
        'redirect' => env('GITHUB_CALLBACK_URL'),
    ],
]

Then you need to add github client id and client secret in .env file:

.env

GITHUB_CLIENT_ID=Ov23lianjXFMjc...
GITHUB_CLIENT_SECRET=b30d1984c9bd180486ec29ac42e269e61b...
GITHUB_CALLBACK_URL=http://localhost:8000/auth/github/callback

Step 5: Add github_id Column

In this step, first, we have to create a migration to add the github_id in your user table. So let's run the below command:

php artisan make:migration add_github_id_column

Migration

<?php

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

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

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        //
    }
};

Now, run the migration command:

php artisan migrate

Update mode like this way:

app/Models/User.php

<?php

namespace App\Models;

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',
        'github_id'
    ];

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}

Step 6: Create Routes

After adding the `github_id` column, first, we have to add new routes for Github login. So let's add the below route in the `routes.php` file.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\GithubController;
  
Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
  
Route::controller(GithubController::class)->group(function(){
    Route::get('auth/github', 'redirectToGithub')->name('auth.github');
    Route::get('auth/github/callback', 'handleGithubCallback');
});

Step 7: Create Controller

After adding the routes, we need to add a method for github authentication. This method will handle the github callback URL, etc. First, put the code below in your GithubController.php file.

app/Http/Controllers/GithubController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
    
class GithubController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGithub()
    {
        return Socialite::driver('github')->redirect();
    }
          
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleGithubCallback()
    {
        try {
        
            $user = Socialite::driver('github')->user();
         
            $findUser = User::where('github_id', $user->id)->first();
         
            if($findUser){
         
                Auth::login($findUser);
        
                return redirect()->intended('home');
         
            }else{
                $newUser = User::updateOrCreate(['email' => $user->email],[
                        'name' => $user->name,
                        'github_id'=> $user->id,
                        'password' => encrypt('123456dummy')
                    ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('home');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Step 8: Update Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/auth/login.blade.php

@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="row mb-3">
                            <label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email 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="row mb-3">
                            <label for="password" class="col-md-4 col-form-label text-md-end">{{ __('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="row mb-3">
                            <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="row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))
                                    <a class="btn btn-link" href="{{ route('password.request') }}">
                                        {{ __('Forgot Your Password?') }}
                                    </a>
                                @endif
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-6 offset-md-4 mt-2">
                               <a class="btn btn-dark" href="{{ route('auth.github') }}"
                                style="display: block;">
                                <svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="40" height="40" viewBox="0 0 30 30">
                                    <path fill="#FFFFFF" d="M15,3C8.373,3,3,8.373,3,15c0,5.623,3.872,10.328,9.092,11.63C12.036,26.468,12,26.28,12,26.047v-2.051 c-0.487,0-1.303,0-1.508,0c-0.821,0-1.551-0.353-1.905-1.009c-0.393-0.729-0.461-1.844-1.435-2.526 c-0.289-0.227-0.069-0.486,0.264-0.451c0.615,0.174,1.125,0.596,1.605,1.222c0.478,0.627,0.703,0.769,1.596,0.769 c0.433,0,1.081-0.025,1.691-0.121c0.328-0.833,0.895-1.6,1.588-1.962c-3.996-0.411-5.903-2.399-5.903-5.098 c0-1.162,0.495-2.286,1.336-3.233C9.053,10.647,8.706,8.73,9.435,8c1.798,0,2.885,1.166,3.146,1.481C13.477,9.174,14.461,9,15.495,9 c1.036,0,2.024,0.174,2.922,0.483C18.675,9.17,19.763,8,21.565,8c0.732,0.731,0.381,2.656,0.102,3.594 c0.836,0.945,1.328,2.066,1.328,3.226c0,2.697-1.904,4.684-5.894,5.097C18.199,20.49,19,22.1,19,23.313v2.734 c0,0.104-0.023,0.179-0.035,0.268C23.641,24.676,27,20.236,27,15C27,8.373,21.627,3,15,3z"></path>
                                </svg>

                                Login with Github
                            </a>
                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/login

Output:

I hope it can help you...

Shares