Share this:

Laravel login with Github instructional exercise, this step-by-step direct clarifies how to coordinated OAuth Github login within the laravel app with the assistance of a third-party composer socialite bundle from scratch.

Social login simplifies the authentication process, social platforms, such as Facebook, Twitter, Google, and LinkedIn, are the most popular and well-known tools for quickly connecting people.

This guide will show you how to use the laravel socialite library to easily integrate or implement Github login.

Without the Laravel socialite package, this laravel socialite GitHub login tutorial example would not be possible.

It provides an easy-to-use, graceful OAuth authentication mechanism for Github, Facebook, Twitter, Google, LinkedIn, GitHub, GitLab, and Bitbucket.

Laravel 9 OAuth Login with Github Example

  • Step 1: Create Laravel App
  • Step 2: Add Database Details in ENV
  • Step 3: Add Jetstream in Laravel
  • Step 4: Install and Setting Up Socialite Pacakage
  • Step 5: Add Github ID in Users Table
  • Step 6: Register Github Client ID and Secret
  • Step 7: Construct Controller
  • Step 8: Create Routes
  • Step 9: Update Login View
  • Step 10: Start Laravel App

Create Laravel App

To create a new Laravel app, use the first command. Make sure you have composer installed on your system:

composer create-project laravel/laravel --prefer-dist laravel-github-login-example

Add Database Details in ENV

Second, edit your database credentials in the .env configuration file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=root
DB_PASSWORD=

Add Jetstream in Laravel

Laravel Jetstream is a classic authentication scaffolding built with Tailwind CSS that makes it simple to create auth templates with Livewire or Inertia scaffolding.

It includes pre-built templates for login, registration, email verification, two-factor authentication, session management, and API support.

With the following command, you can easily instal the jetstream package:

composer require laravel/jetstream

Create auth templates using the following command:

php artisan jetstream:install livewire

Install the following dependencies after that:

npm install

To compile scripts, run the following command:

npm run dev

Finally, run migration with the following command:

php artisan migrate

Install and Setting Up Socialite Pacakage

In this step, you’ll use the provided command to install the socialite library in Laravel:

composer require laravel/socialite

Add socialite services to providers, as well as aliases arrays, in the config/app.php file:

....
....
'providers' => [
    ....
    ....
    Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
    ....
    ....
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
....
....

Add Github ID in Users Table

We must now add the new value to the users’ table in the next imperative task, so use the command to create a new migration file:

php artisan make:migration add_github_social_id_field

After that, update the suggested values in the newly generated migration file in database/migration/xxx_add_github_social_id_field.php.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddGithubSocialIdField extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('github_id')->nullable();
            $table->string('auth_type')->nullable();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('github_id');
           $table->dropColumn('auth_type');
         });
    }
}

Now we must register the value of the newly created migration file in the User model file. As a result, go to the app/Models/User.php file and make the necessary changes.

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

Now that you’ve added new table values, open the console and run the following command to migrate and update the database tables:

php artisan migrate

Register Github Client ID and Secret

You’ll need a Github account to follow along with this tutorial.

To get the Github client id and secret, go to the GitHub developers account after creating the account.

You must create a new OAuth application, which you can do by clicking the Register a new application button.

Fill in the required information to register a new OAuth app when the next screen appears.

You can easily obtain the Client ID and Secrets once the app has been correctly registered.

We now have the GitHub id and secret keys; we must now reach an agreement between laravel and GitHub. Also, as suggested below, register id and secret keys in the config/services.php file:

return [
    ...
    ...
    'github' => [
        'client_id' => 'xxxxx',
        'client_secret' => 'xxxxx',
        'redirect' => 'http://127.0.0.1:8000/auth/github/callback',
    ],
]

Construct Controller

You must create a controller in this step, which will be the locus of the Laravel GitHub Login integration example.

php artisan make:controller GitHubController

Then go to app/Http/Controllers/GitHubController.php and update the provided code as follows:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use Exception;
use Socialite;
use App\Models\User;
class GitHubController extends Controller
{
    public function gitRedirect()
    {
        return Socialite::driver('github')->redirect();
    }
       
    public function gitCallback()
    {
        try {
     
            $user = Socialite::driver('github')->user();
      
            $searchUser = User::where('github_id', $user->id)->first();
      
            if($searchUser){
      
                Auth::login($searchUser);
     
                return redirect('/dashboard');
      
            }else{
                $gitUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'github_id'=> $user->id,
                    'auth_type'=> 'github',
                    'password' => encrypt('gitpwd059')
                ]);
     
                Auth::login($gitUser);
      
                return redirect('/dashboard');
            }
     
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Create Routes

In this step, we create two routes in Laravel to handle the GitHub login. As a result, in the routes/web.php file, add the following code:

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\GitHubController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
 
Route::get('auth/github', [GitHubController::class, 'gitRedirect']);
Route::get('auth/github/callback', [GitHubController::class, 'gitCallback']);

Integrate Socialite Github Login

We’ve almost finished; in the next step, we’ll open the views/auth/login.blade.php file and add the Github login button to the login template, as well as bind the route in Laravel that requests Github OAuth login.

<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>

            {{-- Login with GitHub --}}
            <div class="flex items-center justify-end mt-4">
                <a class="btn" href="{{ url('auth/github') }}"
                    style="background: #313131; color: #ffffff; padding: 10px; width: 100%; text-align: center; display: block; border-radius:3px;">
                    Login with GitHub
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Start Laravel App

Run the command to start the laravel social login project in the final step.

php artisan serve

You can use the following url to log in to GitHub:

http://127.0.0.1:8000/login

Conclusion

We’ve completed the laravel social login tutorial; in this tutorial, we learned how to use the laravel socialite package to integrate Github login into a laravel application.

Furthermore, we created the flawless authentication UI templates using the JetStream package in Laravel.

Share this:

Categorized in: