How to Login with Github Account Using Laravel 10?

Apr 13, 2023 . Admin



Hi friends,

Today I will use a Github account example to demonstrate how to login to Laravel 10. I'll teach how to sign in to the Laravel 10 Application using a GitHub account in this example. To log into the Laravel 10 Application with a GitHub account, we'll use the Socialite module from Laravel 10. I'll be demonstrating the Laravel 10 login system with Github in this tutorial.

Today, we'll cover how to easily authenticate users using the GitHub Login and how to integrate a GitHub social login to your Laravel 10 application.

We know that the user feels so bored to give manually inputting their information, like name, email password, etc. So if we use the Socialite login system, then no need to give their data.

Step 1: Download Laravel

Let us begin the tutorial by installing a new Laravel application. if you have already created the project, then skip the following step.

composer create-project laravel/laravel example-app
Step 2: Install JetStream

Now, in this step, we need to use the composer command to install jetstream, so let's run the bellow command and install the bellow library.

composer require laravel/jetstream

now, we need to create authentication using the below command. you can create basic login, register, and email verification. if you want to create team management then you have to pass the additional parameter. you can see bellow commands:

php artisan jetstream:install livewire

Now, let's node js package:

npm install

let's run the package:

npm run dev

now, we need to run the migration command to create a database table:

php artisan migrate
Step 3: Install Socialite

In the first step, we will install Socialite Package that provides API to connect with the GitHub account. So, first, open your terminal and run bellow command:

composer require laravel/socialite
Step 4: Create Github App

In this step we need the GitHub client id and secret that way we can get information from another user. so if you don't have a GitHub app account then you can create one from here: Github Developers Console. You can find bellow screen, Then click on "New OAuth App" and create a new app:

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

config/services.php
return [
    ....
    'github' => [
        'client_id' => env('GITHUB_CLIENT_ID'),
        'client_secret' => env('GITHUB_CLIENT_SECRET'),
        'redirect' => 'http://localhost:8000/auth/github/callback',
    ],
]

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

.env
GITHUB_CLIENT_ID=xyz
GITHUB_CLIENT_SECRET=123
Step 5: Add Github App

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

php artisan make:migration add_github_id_column_to_users
database/migrations/add_github_id_column_to_users.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.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('github_id')->nullable();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
};

Update mode like this way:

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;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
  
class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'github_id'
    ];
  
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];
  
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
  
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}
Step 6: Add Routes

After adding the github_id column first we have to add a new route for GitHub login. so let's add the below route in the routes.php file.

<?php
  
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\GithubController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('/', function () {
    return view('welcome');
});
  
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
    return view('dashboard');
})->name('dashboard');
  
Route::controller(GithubController::class)->group(function(){
    Route::get('auth/github', 'redirectToGithub')->name('auth.github');
    Route::get('auth/github/callback', 'handleGithubCallback');
});
Step 7: Add Controller

After adding a route, we need to add the method of GitHub auth that method will handle GitHub callback URLs and etc, first put the below code on 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('dashboard');
         
            }else{
                $newUser = User::updateOrCreate(['email' => $user->email],[
                        'name' => $user->name,
                        'github_id'=> $user->id,
                        'password' => encrypt('123456dummy')
                    ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('dashboard');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}
Step 8: Update Blade File

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

resources/views/auth/login.blade.php
<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 for="email" value="{{ __('Email') }}" />
                <x-jet-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>
  
            <div class="mt-4">
                <x-jet-label for="password" value="{{ __('Password') }}" />
                <x-jet-input id="password" class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>
  
            <div class="block mt-4">
                <label for="remember_me" class="flex items-center">
                    <x-jet-checkbox id="remember_me" 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">
                    {{ __('Log in') }}
                </x-jet-button>
            </div>
            <div class="flex items-center justify-end mt-4">
                <a class="btn" href="{{ route('auth.github') }}"
                    style="background: black; padding: 10px; width: 100%; text-align: center; display: block; border-radius:4px; color: #ffffff;">
                    Login with GitHub
                </a>
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>
Run Laravel App:

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

php artisan serve

Now, you have to open a web browser, type the given URL and view the app output:

http://localhost:8000/login
Output:

I hope it can help you...

#Laravel 10