Laravel-9 Tutorial – Laravel 9 Socialite Login with Github Example Tutorial

Laravel login with Github tutorial; this step-by-step guide explains how to integrate OAuth Github login in the laravel app with the help of a third-party composer socialite package from scratch.

Social login makes the authentication process facile; social platforms, be it Facebook, Twitter, Google, LinkedIn, are the most common and notable tools which establish the people connection quickly.

This guide helps you learn Github login integration or implementation easily using the laravel socialite library.

This laravel socialite GitHub login implementation tutorial example is not possible without the Laravel socialite package.

It offers an intuitive, graceful mechanism for OAuth authentication not just with Github but also for 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

Invoke the very first to create a new laravel app, make sure you have composer configured on your system:

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

Add Database Details in ENV

Secondly, open .env configuration file and add your database credentials:

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

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Add Jetstream in Laravel

Laravel Jetstream is a quintessential authentication scaffolding crafted with Tailwind CSS and allows you to build auth templates with Livewire or Inertia scaffolding effortlessly.

It gives you pre-defined login, registration, email verification, two-factor authentication, session management, API support templates.

You can easily install jetstream package with suggested command:

composer require laravel/jetstream

Next, use command to create auth templates:

php artisan jetstream:install livewire

Subsequently, install needed dependencies:

npm install

Execute command to compile scripts:

npm run dev

Eventually run migration with recommended command:

php artisan migrate

Install and Setting Up Socialite Pacakage

In this step, you will install socialite library in laravel using the provided command:

composer require laravel/socialite

Get inside the config/app.php file then add socialite services in providers, as well as aliases arrays:

....
....
'providers' => [
    ....
    ....
    LaravelSocialiteSocialiteServiceProvider::class,
],
'aliases' => [
    ....
    ....
    'Socialite' => LaravelSocialiteFacadesSocialite::class,
],
....
....

Add Github ID in Users Table

In the next imperative task, we have to add the new value inside the users’ table, hence use the command to create a new migration file:

php artisan make:migration add_github_social_id_field

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


use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class AddGithubSocialIdField extends Migration
{
    
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('github_id')->nullable();
            $table->string('auth_type')->nullable();
        });
    }
    
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('github_id');
           $table->dropColumn('auth_type');
         });
    }
}

Now, we have to register the newly created migration file’s value inside the User model file. Consequently, head over to the app/Models/User.php file and update the values.


namespace AppModels;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelFortifyTwoFactorAuthenticatable;
use LaravelJetstreamHasProfilePhoto;
use LaravelSanctumHasApiTokens;
class User extends Authenticatable
{
    use HasFactory, Notifiable;
    
    protected $fillable = [
        'name',
        'email',
        'password',
        'github_id',
        'auth_type',
    ];
    
    protected $hidden = [
        'password',
        'remember_token',
    ];
    
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Now new table values have been added, just open the console and execute the command to run migration and update the database tables:

php artisan migrate

Register Github Client ID and Secret

In order to get along with this tutorial, you must have a Github account.

When you create the account, you have to visit the GitHub developers account to get the Github client id and secret.

You have to create a new OAuth application, so create on Register a new application button.

Github developer account

When you react to the next screen, fill in the required information to register a new OAuth app.

Register OAuth Applicaiton

Once the app is registered correctly, then you can get the Client ID and Secrets effortlessly.

Github ID & Secret

We have got the GitHub id and secret keys; thereupon, we have to make the consensus between laravel and GitHub. Further, register id and secret keys in the config/services.php file as suggested below:

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

Construct Controller

In this step, you have to create a controller, and it will be the locus of the Laravel GitHub Login integration example.

php artisan make:controller GitHubController

Next, head over to app/Http/Controllers/GitHubController.php and recklessly update the provided code:


namespace AppHttpControllers;
use IlluminateHttpRequest;
use Auth;
use Exception;
use Socialite;
use AppModelsUser;
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 to handle the login with GitHub in laravel. Hence, add the following code in routes/web.php file:


use IlluminateSupportFacadesRoute;
use AppHttpControllersGitHubController;

 
Route::get('auth/github', [GitHubController::class, 'gitRedirect']);
Route::get('auth/github/callback', [GitHubController::class, 'gitCallback']);

Integrate Socialite Github Login

We have covered almost everything; in the subsequent step, we will open the views/auth/login.blade.php file, and add the Github login button in the login template and bind the route which requests Github OAuth login in laravel.

<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

In the final step, run the command to start the laravel social login project.

php artisan serve

You can login with GitHub using the below url:

http://127.0.0.1:8000/login

Laravel Socialite Github Login

Conclusion

We have successfully completed the laravel social login tutorial; in this tutorial, we learned how to integrate Github login in the laravel application using the laravel socialite package.

Moreover, we used the JetStream package in laravel to create the flawless authentication UI templates.

Leave a Reply

Your email address will not be published. Required fields are marked *