Hello Devs,
In this tutorial, we will learn Laravel 8 login with Github Example Tutorial
If your application has a login with social media then it becomes really awesome. you will get more people to connect with your website because most people do not want to fill in sign-up or sign-in from their personal ids or something like that.
Follow this step-by-step guide below.
Step 1 : Install Laravel 8
composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3 : Install Jetstream
Step 4 : Install Socialite
composer require laravel/socialite
config/app.php
....
'providers' => [
....
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
....
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
....
Step 5: Create Github Api
- Create a Github account here if not created before, Github
- Open Github
- Now you have to click on Developer settings
- Next, you have to click on the OAuth Apps
- Here you have to click on Register a new application
- Then you have to create on Register a new OAuth application
- Now Ready your Github API
config/services.php
return [
....
'github' => [
'client_id' => 'app id',
'client_secret' => 'add secret',
'redirect' => 'http://your-callback-url',
],
]
Step 6: Add Database Column
php artisan make:migration add_github_id_column
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddGithubIdColumn 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()
{
Schema::table('users', function ($table) {
$table->dropColumn('github_id');
});
}
}
Update mode:
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 array
*/
protected $fillable = [
'name',
'email',
'password',
'github_id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* @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 7: Create Routes
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\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('auth/github', [GithubController::class, 'redirectToGithub']);
Route::get('auth/github/callback', [GithubController::class, 'handleGithubCallback']);
Step 8: Create Controller
app/Http/Controllers/Auth/GithubController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Socialite;
use Auth;
use Exception;
use App\Models\User;
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('/home');
}else{
$newUser = User::create([
'name' => $user->name,
'email' => $user->email,
'github_id'=> $user->id,
'password' => encrypt('123456dummy')
]);
Auth::login($newUser);
return redirect('/home');
}
} catch (Exception $e) {
dd($e->getMessage());
}
}
}
Step 9: Update Blade File
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 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>
<a href="{{ url('auth/github') }}" style="margin-top: 0px !important;background: green;color: #ffffff;padding: 5px;border-radius:7px;" class="ml-2">
<strong>Login With Github</strong>
</a>
</div>
</form>
</x-jet-authentication-card>
</x-guest-layout>
run this command for a quick run:
php artisan serve
open bellow URL on your browser:
localhost:8000/login
May this example will help you.