Why Use Socialite for GitHub Authentication in Laravel?
Laravel Socialite is the official, first-party package designed specifically to make OAuth-based social authentication simple, consistent, and secure in Laravel applications. When implementing GitHub login (or any other provider like Google, GitLab, etc.), Socialite stands out as the preferred choice over building the OAuth flow from scratch. Here's why developers choose it:
- Drastically Reduces Complexity and Boilerplate Code
Implementing OAuth manually involves handling redirects, authorization codes, access tokens, token exchanges, error handling, and provider-specific quirks — often hundreds of lines of code. Socialite abstracts all of this into just a few elegant method calls:
This means you can go from zero to working GitHub login in minutes instead of hours or days.return Socialite::driver('github')->redirect(); // and later $user = Socialite::driver('github')->user(); - Saves Significant Development Time
By handling the heavy lifting (OAuth request/response cycles, signature generation, redirects, and user data retrieval), Socialite lets you focus on your application's core features rather than reinventing authentication logic. - Consistent Interface Across Multiple Providers
Whether you're adding GitHub, Google, LinkedIn, GitLab, Slack, or others, the API remains the same: driver('provider'), redirect(), user(), stateless(), scopes, etc. This makes it easy to support multiple social logins without duplicating code. - Built-in Support for GitHub (and Many Others)
GitHub is one of the natively supported providers, so no extra adapters are needed. You get immediate access to key user data like ID, name, email, nickname, avatar, access token, and refresh token — perfect for creating or linking user accounts in your database. - Security Best Practices Baked In
Socialite follows OAuth 2.0 standards correctly, helping avoid common pitfalls like insecure redirects, token leakage, or improper state validation. It also supports stateless mode (great for APIs/SPAs) and easy scope customization (e.g., limiting to user:email or adding repo access). - Seamless Integration with Laravel's Ecosystem
It pairs perfectly with Laravel's authentication system — use Auth::login($user) after retrieving the Socialite user, and combine it with updateOrCreate for smooth user creation/updates. It also works flawlessly with Breeze, Jetstream, or custom auth setups. - Testing-Friendly
Socialite includes built-in fakes and mocking capabilities, so you can test your GitHub login flow without hitting real GitHub servers — ideal for reliable unit and feature tests.
In 2025–2026, with increasing focus on user experience, security, and rapid development, Laravel Socialite delivers the fastest path to production-ready GitHub authentication while keeping your code clean, maintainable, and secure. Unless you have highly custom OAuth needs (rare for standard GitHub login), Socialite is the recommended, battle-tested solution used by thousands of Laravel applications worldwide.

Table Of Content
1 Prerequisites
2.) MySql
3.) Github Account
2 Introduction
3 Create a New Laravel 11 Project
3.1 Install Laravel Project
Use the following command to install new Laravel Project.
composer create-project laravel/laravel github-auth-app
Then, navigate to your project directory:
cd github-auth-app
3.2 Configure MySql Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel11
DB_USERNAME=root
DB_PASSWORD=
4 Install Laravel Breeze & Socialite
4.1 Install Breeze Package
composer require laravel/breeze --dev
After Composer has installed the Laravel Breeze package, you should run the breeze:install Artisan command. This command publishes the authentication views, routes, controllers, and other resources to your application.
php artisan breeze:install
php artisan migrate
npm install
npm run dev
4.2 Install Socialite Package
composer require laravel/socialite
5 Create a GitHub OAuth App
5.1 Login into GitHub Account
5.2 Register new OAuth Application

Click "Developer Settings" from Left Side menu

Go To OAuth apps then Click "New OAuth App" Button

Fill all the details in "Register a new OAuth application" Form, also fill the Authorization callback URL. This is the URL that we will use to redirect user after they choose their GitHub account to login to our web. For example here I use http://127.0.0.1:8000/callback/github for the callback URL.

After clicking on Register application button , you will receive a Client ID and Client Secrets. copy these keys into your .env file.
6 Configure Credentials
6.1 In .env
GITHUB_CLIENT_ID=Your Client ID
GITHUB_CLIENT_SECRET=Your Client Secret
GITHUB_REDIRECT_URI=http://127.0.0.1:8000/callback/github
6.2 In config/services.php
<?php
return [
// Other services ..
'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => env('GITHUB_REDIRECT_URI'),
],
];
?>
6.3 Add github_id to Users Table
php artisan make:migration add_github_id_to_users
In the generated new migration file, update the up and down methods as described below:
database/migrations/2024_04_27_120820_add_github_id_to_users.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('github_id')->after('password')->nullable()->unique();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('github_id');
});
}
};
Use the following command to run the migration to update your database.
php artisan migrate
6.4 Update the User Model
app/Models/User.php
<?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',
'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',
];
}
}
?>
7 Create GitHub Authentication Controller
php artisan make:controller Auth/GithubController
app/Http/Controllers/Auth/GithubController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use Exception;
class GithubController extends Controller
{
public function redirect()
{
return Socialite::driver('github')->redirect();
}
public function callback()
{
try {
$githubUser = Socialite::driver('github')->user();
$user = User::updateOrCreate(
['github_id' => $githubUser->id],
[
'name' => $githubUser->name ?? $githubUser->nickname,
'email' => $githubUser->email,
'github_token' => $githubUser->token,
'github_refresh_token' => $githubUser->refreshToken,
// No password needed for social users; guard against null
'password' => bcrypt(str_random(16)), // or leave null + custom guard
]
);
Auth::login($user);
return redirect('/dashboard');
} catch (Exception $e) {
// In production: log error, show friendly message
return redirect('/login')->with('error', 'GitHub login failed. Please try again.');
}
}
}
?>
Best Practices Note: Avoid hardcoded/fixed passwords. Use updateOrCreate (official recommendation) and store tokens for future API use. Consider email verification if email is provided.
8 Define Routes (routes/web.php):
routes/web.php
use App\Http\Controllers\Auth\GithubController;
Route::get('/auth/github', [GithubController::class, 'redirect'])->name('auth.github');
Route::get('/auth/github/callback', [GithubController::class, 'callback']);
9 Add "Login with GitHub" Button
<div class="mt-6 text-center">
<a href="{{ route('auth.github') }}" class="inline-flex items-center px-4 py-2 bg-gray-900 text-white rounded hover:bg-gray-800">
<svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 0C4.477 0 0 4.484 0 10.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0110 4.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0020 10.017C20 4.484 15.522 0 10 0z" clip-rule="evenodd"/></svg>
Login with GitHub
</a>
</div>
10 Folder Structure
11 Run Laravel Server to Test the App
php artisan serve
Visit /login, click the button, authorize on GitHub, and get redirected to dashboard.
Best Practices & Security Considerations
- Use HTTPS in production.
- Store tokens securely if using GitHub API later.
- Handle cases where email is null (GitHub private emails).
- Add rate limiting on auth routes.
- Use named routes and middleware for better maintainability.
12 Conclusion
Written by Revathi M
PHP Developer & Technical Writer · 10+ years building web applications with CodeIgniter and Laravel
Revathi specializes in PHP backend development, authentication systems, and REST API design. She writes practical, production-tested tutorials at Get Sample Code to help developers build secure applications faster.
Frequently Asked Questions
You need PHP 8.2 or higher, Composer, a MySQL database, and a GitHub account to create an OAuth app.
Run `composer create-project laravel/laravel github-auth-app`, then `cd github-auth-app`.
Install Breeze with `composer require laravel/breeze --dev`, then `php artisan breeze:install`, `php artisan migrate`, `npm install`, and `npm run dev`. Install Socialite with `composer require laravel/socialite`.
Go to GitHub Settings > Developer settings > OAuth Apps > New OAuth App. Fill in details and set the Authorization callback URL to `http://127.0.0.1:8000/callback/github`.
Add `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, and `GITHUB_REDIRECT_URI=http://127.0.0.1:8000/callback/github` to the `.env` file. Then add the 'github' array to `config/services.php`.
Run `php artisan make:migration add_github_id_to_users`, add `$table->string('github_id')->nullable()->unique();` in the migration, then run `php artisan migrate`. Update the User model's `$fillable` array to include 'github_id'.
Run `php artisan make:controller GithubSocialiteController`, then implement `redirectToGithub()` to redirect using Socialite and `handleCallback()` to handle the user response, find or create the user, and log them in.
In `routes/web.php`, add `Route::get('auth/github', [GithubSocialiteController::class, 'redirectToGithub']);` and `Route::get('callback/github', [GithubSocialiteController::class, 'handleCallback']);`.
In the login view (e.g., from Breeze), add <a href=`{{ url('auth/github') }}`> <img src='images/github_button.png'> </a> or a similar button linking to `/auth/github`.
The callback URL in the GitHub OAuth app settings must exactly match the `GITHUB_REDIRECT_URI` in `.env` and the callback route (e.g., `http://127.0.0.1:8000/callback/github`).
Verify the Client ID and Secret are correct, run `composer dump-autoload`, and ensure the redirect URI matches exactly in both GitHub app and Laravel config.
Wrap the callback in try-catch and log exceptions (e.g., `dd($e->getMessage())`). Common issues: invalid credentials, mismatched redirect URI, or network problems.
The tutorial uses `github_id` for lookup/find-or-create. If email is available, you can modify the query to match on email or combine both for account merging.
Run `php artisan serve`, visit `http://127.0.0.1:8000`, go to login, click the GitHub button, and complete the OAuth flow.
