Skip to content
Itstuffsolutions

Itstuffsolutions

  • Home
  • post
  • About Us
  • Contact Us
Laravel 12 Socialite Login with GitHub OAuth Example

Laravel 12 Socialite Login with GitHub OAuth Example

August 16, 2025 Itstuffsolutions

In this tutorial titled “Laravel 12 Socialite Login with GitHub OAuth Example”, you will learn how to integrate GitHub login in Laravel 12 using Laravel Socialite. We will be using Laravel Bootstrap scaffolding auth for authentication, but you can also use Jetstream or Breeze if you prefer.

In this Laravel 12 tutorial, we will install the Socialite package, create a GitHub OAuth app, and integrate it with the login form so users can easily log in using their GitHub accounts.

Login with Socialite is very useful because many users do not want to spend time filling out long registration forms. In today’s era, most people already have accounts on social media or developer platforms, so allowing them to log in via GitHub makes the process quick and seamless.

By offering GitHub login, you can make your application more attractive, especially for developers. Socialite also supports other popular providers like Google, Facebook, Twitter, LinkedIn, and more — so you can easily add multiple social login options to suit your audience.

Prerequisites

  • Composer installed
  • Basic knowledge of Laravel routes, controllers, and authentication
  • A GitHub account

Steps For Laravel 12 Socialite Login with GitHub OAuth Example

  • Step 1: Install Laravel 12
  • Step 2: Install Laravel UI
  • Step 3: Install Laravel Socialite
  • Step 4: Create GitHub OAuth App
  • Step 5: Configure GitHub OAuth Credentials
  • Step 6: Add github_id Column to Users Table
  • Step 7: Create Routes
  • Step 8: Create Controller For GitHub Login
  • Step 9: Add GitHub Login Button in Blade File
  • Step 10: Run the Application

Step 1: Install Laravel 12

In this step, we’ll create a new Laravel project. If you’ve already installed Laravel 12 project , you can skip this step. Otherwise, run the following command to create a fresh Laravel application:

	
composer create-project laravel/laravel laravel-12-socialite-login-with-github-oauth-example

Navigate to project folder

cd laravel-12-socialite-login-with-github-oauth-example

Step 2: Install Laravel UI

In this step, We will install Laravel UI for Bootstrap-based authentication scaffolding via composer:

 composer require laravel/ui

Generate Bootstrap auth using the below command:

php artisan ui bootstrap --auth

Install npm dependencies and compile assets:

npm install && npm run dev

These commands will create authentication routes and views for login, registration, and password reset, apply a Bootstrap-based frontend layout, and get your application ready for Socialite integration.

Note: If your project is built with a frontend starter kit such as Laravel Jetstream or Laravel Breeze, you can skip the Bootstrap UI installation process. These packages already come with authentication scaffolding out of the box.

Step 3: Install Laravel Socialite

Once Laravel authentication is set up, the next step is to install the Socialite package via Composer to handle GitHub OAuth login . Socialite offers a simple API for authenticating users through various platforms such as GitHub, Facebook, Google, and more:

composer require laravel/socialite

Step 4: Create GitHub OAuth App

  • Log in to your GitHub account.
  • Click your profile icon on the top-right, go to Settings > Developer settings > OAuth Apps.
  • Click “New OAuth App“.
  • Fill in the details:
    • Application name: ItstuffsolutionsApp
    • Homepage URL: http://localhost:8000
    • Authorization callback URL: http://localhost:8000/auth/github/callback
  • After saving, copy your Client ID and Client Secret.

After logging in, click your profile icon at the top-right corner, then select Settings from the menu as shown in the image below:

Laravel 12 Socialite Login with GitHub OAuth Example
Select “Settings” from the profile menu

Go to https://github.com/settings/profile and click Developer settings from the left-hand menu, as shown in the image.

In the profile settings page, click Developer settings from the left-hand menu.

After clicking Developer settings, you will see a page like the image below. From the left-hand menu, select OAuth Apps and then click the Create OAuth App button.

Create New GitHun OAuth App
Create New GitHun OAuth App

After clicking New GitHub App, a screen similar to the one below will appear. In the Register a new OAuth App section, provide the GitHub app name, Homepage URL, and Authorization Callback URL and click register application button.

Laravel 12 Socialite Login with GitHub OAuth Example
Fill out the OAuth form to create a new App.

After registering the application, you will see the Client ID and a button labeled Generate a new client secret. Click the button to generate the client secret, then copy and save it.

⚠️ Remember to save the client secret key, because it will only be shown once.

Copy GitHub App Credentials
Copy GitHub App Credentials

Read Also : Laravel 12 Socialite Login With Google Account Example

Step 5:Configure GitHub OAuth Credentials

Now that you have successfully created a GitHub OAuth app, the next step is to configure its credentials in the .env file and config/services.php. Follow the steps below to add them.

1. Add Credentials in .env File

Open your project’s .env file:

GITHUB_CLIENT_ID=your_client_id
GITHUB_CLIENT_SECRET=your_client_secret
GITHUB_REDIRECT=http://localhost:8000/auth/github/callback

Client ID : Provided by GitHub when you created the OAuth app.

Client Secret : Generated once when you clicked Generate a new client secret.

Redirect URL : Must be the same as what you entered in GitHub OAuth settings.

⚠️ Important: If the Redirect URL in your .env file doesn’t match the one configured in GitHub, authentication will fail.

2. Update config/services.php

Next, open the config/services.php file and register GitHub inside the returned array:

'<?php
 
 return [
    //Other services
'   'github' => [
    'client_id' => env('GITHUB_CLIENT_ID'),
    'client_secret' => env('GITHUB_CLIENT_SECRET'),
    'redirect' => env('GITHUB_REDIRECT'),
       ],
     ];

This tells Laravel to use the credentials from your .env file whenever a user tries to log in via GitHub.

Step 6: Add github_id Column to Users Table

In this step, we will add a github_id column to the users table to store the unique GitHub ID for users who log in through GitHub.

Run the following Artisan command given below , To create the migration file:

php artisan make:migration add_github_id_to_users_table

This command will create a new migration file inside the database/migrations Folder. Open the generated file and update it with the required schema changes. Once the file is ready, add the following code.

In this migration file, we updated the up method to add a github_id column after the email column. The column is set to nullable, which means if a user registers or logs in using another method instead of GitHub, the database will not throw an error.

database/migrations/2025_08_16_045523_add_github_id_in_users_table.php

<?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 (Blueprint $table) {
            $table->string('github_id')->nullable()->after('email');
        });
    }

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

Now Run the following command to create github_id column in users table:

php artisan migrate

Update Users Model

Now Open app/Models/User.php , update the $fillable property by adding github_id column. This ensures that the ID can be mass-assigned and saved to the database.

<?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<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'github_id', //add this line
    ];

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

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

Step 7: Create Routes

In this step, we will define two routes for GitHub OAuth login: the first route will redirect the user to GitHub, and the second will handle the callback to authenticate the user. All other authentication routes are already included through the Bootstrap auth scaffolding.

&lt;?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\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 8: Create Controller For GitHub Login

Run the following command to generate a GitHub OAuth controller inside the App/Http/Controllers/Auth directory:

php artisan make:controller Auth/GitHubController

Now open the App/Http/Controllers/Auth/GitHubController.php and add the following code. In this controller, the redirectToGitHub() method redirects the user to the GitHub login page, while the handleGitHubCallback() method handles the callback, authenticates the user, creates a new record for first-time users, and updates the record for existing users. If any exception occurs during the process, the user will be redirected back to the login page with an error message.

<?php

namespace App\Http\Controllers\Auth;

use Laravel\Socialite\Facades\Socialite;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Models\User;
use Exception;

class GitHubController extends Controller
{
     public function redirectToGitHub(){
        //redirect to github 
     return Socialite::driver('github')->redirect();
    }

     public function handleGitHubCallback(Request $request)
    {
       try{

         $github_user = Socialite::driver('github')->user();
          
          // If the user exists, update their record; otherwise, create a new one
          $user = User::updateOrCreate([
            'github_id' => $github_user->id,
            ], [
                'name' => $github_user->name,
                'email' => $github_user->email,
                'password' => bcrypt('1234test'),
            ]);

         Auth::login($user);
         return redirect()->route('home');

        } catch (Exception $e) {
                return redirect('/login')->with('error', 'GitHub login failed. Please try again.');
            }
    }
}

Step 9: Add GitHub Login Button in Blade File

In this step, we will update the login blade by adding a GitHub login button with the GitHub icon, along with displaying an error message if the GitHub login fails.

Open resources/views/auth/login.blade.php and add the code below:

@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">
                    @if (session('error'))
                        <div class="alert alert-danger">
                            {{ session('error') }}
                        </div>
                    @endif
                    <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-8 offset-md-4">
                                <br/>
                                <a href="{{ route('auth.github') }}" class="btn btn-light border-dark">
                                    <img height="32" width="32" src="https://cdn.jsdelivr.net/npm/simple-icons@v15/icons/github.svg" alt="GitHub logo"> Login With GitHub
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 10: Run the Application

Once you have completed all the steps successfully, run the Artisan command to start the Laravel development server.

php artisan serve

Then open your browser, paste the following URL, and press Enter. You should now see a screen similar to the one below.

http://localhost:8000/login
GitHub OAuth Login Form
GitHub OAuth Login Form

Click the “Login with GitHub” button and authorize the application on GitHub. After successfully login you will be redirected back to your application, logged in as the GitHub user. 

Conclusion

Adding GitHub login to your Laravel 12 app with Socialite is simpler than you might think! In this laravel tutorial, we covered how to install Socialite, set up GitHub OAuth, and implement a smooth authentication flow.. This integration saves users from dealing with extra passwords and makes your app more convenient to access. Whether you’re creating a blog, an e-commerce platform, or any kind of web application, social logins like GitHub can significantly improve user engagement. I hope you found this guide useful—now it’s your turn to add GitHub login to your Laravel project!

Frequently Asked Questions (FAQs)

Q1: What is Socialite in Laravel 12?

Socialite is Laravel’s official package that provides a simple, expressive interface for OAuth authentication with providers like GitHub, Google, Facebook, etc.

Q2: What if the Github login fails?

Check your GitHub Client ID, GitHub Client Secret, and redirect URI in the .env file. Ensure the URI matches exactly one configured in GitHub. The controller also redirects to the login page with an error message if it fails.

Q3: How do I add multiple providers (Google, GitHub, Twitter) at once?

Yes, you can integrate multiple OAuth providers (like Google, GitHub, Twitter, Facebook, LinkedIn) using Laravel Socialite in the same application. You can handle multiple providers with one setup. Add them in config/services.php, create a single route like:

Route::get('login/{provider}', [SocialLoginController::class, 'redirectToProvider']);
Route::get('login/{provider}/callback', [SocialLoginController::class, 'handleProviderCallback']);

Then in your controller use:

$user = Socialite::driver($provider)->user();

This lets you log in with Google, GitHub, Twitter, etc. using the same logic.

Q4: How do I handle callback URLs across local, staging, and production?

Each OAuth app must list exact redirect URIs for each environment, so configure distinct URLs (e.g., localhost, staging domain, production domain) in provider dashboards and map them via environment variables in Laravel.

Verify that the redirect parameter exactly matches the registered URL to avoid provider errors during the authorization code exchange.

Q5: How can I prevent duplicate users when the same person uses different providers?

Always match users by email (or another unique identifier) before creating a new record. This way, if the same person logs in with Google or GitHub (same email), they’ll be linked to one account instead of creating duplicates.

Related

Categories Laravel, Auth, Laravel 12, Socialite Login Tags github login, laravel, laravel 12, socialite login
Laravel 12 Socialite Login With Google Account Example
Laravel 12 How to Change Date Format Example

Recent Posts

  • Laravel 12 How to Change Date Format Example
  • Laravel 12 Socialite Login with GitHub OAuth Example
  • Laravel 12 Socialite Login With Google Account Example
  • Laravel 12 Generate Fake Data using Factory Tinker
  • Laravel 12 Toastr JS Notifications Example

Categories

  • Auth
  • Change Date Format
  • collection
  • Fake Data
  • Helper Function
  • Laravel
  • Laravel 12
  • Laravel Eloquent
  • migration
  • Rollback
  • Socialite Login
  • Toastr Notifications
Logo
  • About Us
  • Contact Us

© 2025 All Rights Reserved

  • Disclaimer
  • Privacy Policy