Github is very popular for software development and version control using Git. It provides the distributed version control, source code management (SCM), bug tracking, and many more features. Also, you can use its API for creating the Github Login for any web or mobile application. While implementing this awesome functionality, you will require to have an app in Github. Today, in this post, I will be showing you to create the Github Login in Laravel 8. In Laravel 8, we will be using the socialite package. This package will manage the functionality at the application level. Rest, the OAuth login authorization will be managed by Github. I have already shared the tutorial on Google Login, Facebook Login, LinkedIn Login, and Twitter Login. So, let’s begin by creating a new project in Laravel 8.
Prerequisites
For creating the new project in Laravel 8, your system must meet the following requirements-
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Once, you are ready, create a new project using the composer.
Create a Project in Laravel 8 For Github Login
Open the terminal or command prompt. Now, enter the below command to start with a new project.
composer create-project --prefer-dist laravel/larvel laravel-socialite
The above command will create a new project as showing below.
After creating the project, it required a database connection. Hence, firstly, create a new database in MySQL. Secondly, configure the database credentials in Laravel 8 project.
Create and Configure Database
Open the MySQL and create a new database there. For database management, I am using the MySQL command line. You can use phpMyAdmin or MySQL Workbench. It is totally up to you whatever you want to use.
CREATE DATABASE laravel_socialite;
After creating the database, come back to the project. Open the .env file and replace the below credentials in the DB section.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_socialite
DB_USERNAME=root
DB_PASSWORD=root
After the database configuration completed, let’s install the Auth scaffolding for the user authentication.
Install UI Auth in Laravel 8 For Github Login
For managing the user authentication, we will be using the default authentication system. Laravel provides various packages for the authentication system. Here, I will be using the very basic auth that is UI auth in Laravel 8. To install the UI Auth package, let’s hit the below command.
composer require laravel/ui
The above command will install the UI auth package inside the project.
After installing the UI auth package, let’s add the Auth scaffolding for it.
php artisan ui vue --auth
The auth scaffolding will ask to install the npm. The npm will provide the frontend dependencies for the layout designs.
npm install && npm run dev
After running the npm dev command, it will build a CSS and js file in the project.
In the next step, we will install the socialite package in our project.
Install Laravel Socialite Package
The socialite package will make synchronization of social networks with our web application. Here, we are creating a Github login. Hence, it will connect our web application with the Github application. Therefore, to install the socialite package hit the below command in the terminal.
composer require laravel/socialite
This command will install the socialite package.
Now, after installing the package, it will require to add in the provider list.
Add Provider and Alias for Socialite Package
To add the provider for the socialite package, just navigate to the config/app.php. You will find the providers array and aliases array. So, just add the below line one by one.
'providers' => [
…
…
…
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
…
…
…
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
Now, we are moving to the most important step for creating the app in the Github.
Create and Configure App in Github
For creating the Github app, just login your profiie and then go to the Github Profile Settings. Here, you will find the applications tab, so just click on that and you will have the below page. Now, create a new application by giving the app name, homepage URL, and the callback URL.
After filling the required details, register the application. Now, it will provide you the App Id and secret key. So, just copy it and move back to the Laravel application.
Configure the Github App in Laravel Services
Open the config/services.php file and put the below array there. But, don’t forget to replace the client id and secret with your Github app credentials. Also, I have set the redirect URL that is the same which is registered in the Github App.
'github' => [
'client_id' => 'GITHUB_APP_ID',
'client_secret' => 'GITHUB_APP_SECRET_KEY',
'redirect' => 'http://localhost:8000/auth/github-callback',
],
Add Column in Users Table For Github
Here, I am going to create a new migration file for adding one column in users table. The main concern for creating a new column is to store the Github user id in the table. You can use the same migration but you will have to alter the migration by adding the column there.
Hence, hit the below command for creating a new column in the users table.
php artisan make:migration add_github_id_column_in_users_table --table=users
After creating the migration, let’s put a new column as github id. You can take a look at the below file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddGithubIdColumnInUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('github_id')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('github_id');
});
}
}
In the next step, you will require migrating the tables by hitting the migrate command.
php artisan migrate
Also, you will have to set the fillable data for this newly added column.
<?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 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',
];
}
Create a Controller For GitHub Login
To create the functionality for the Github login, you will need the controller.
php artisan make:controller SocialiteAuthController
Now, put the below snippet in the controller.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Socialite;
use Illuminate\Support\Facades\Auth;
use Exception;
class SocialiteAuthController extends Controller
{
public function githubRedirect()
{
return Socialite::driver('github')->redirect();
}
/**
* Facebook login authentication
*
* @return void
*/
public function loginWithGithub()
{
try {
$githubUser = Socialite::driver('github')->user();
$user = User::where('github_id', $githubUser->id)->first();
if($user){
Auth::login($user);
return redirect('/home');
}
else{
$createUser = User::create([
'name' => $githubUser->name,
'email' => $githubUser->email,
'github_id' => $githubUser->id,
'password' => encrypt('test@123')
]);
Auth::login($createUser);
return redirect('/home');
}
} catch (Exception $exception) {
dd($exception->getMessage());
}
}
}
The above functions will require routes.
Add Routes
To make the redirection to the controller function it needs to be connected with the routes. Hence, open the web.php file and put the below routes.
Route::get('github', [SocialiteAuthController::class, 'githubRedirect'])->name('auth/github');
Route::get('/auth/github-callback', [SocialiteAuthController::class, 'loginWithGithub']);
In the last step, you have to create a button for the Github Login.
Create a Button For Github Login Redirection
When you installed the UI Auth package, it generated the auth folders in the views. All the blade files for the auth components are inside this. So, here, you have to open the auth/login.blade.php file. Then add the button or simply replace the below snippet.
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
@csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
<a href="{{ route('auth/github') }}" class="btn btn-primary btn-dark">
{{ __('Login with Github') }}
</a>
</div>
<div class="col-md-8 offset-md-4">
@if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
@endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
Now, you are done and good to check the result of Socialite Github Login.
Check Result of Socialite Github Login
Run the application and check the result in the browser. Firstly, you will have the homepage with auth scaffolding.
So, after clicking on the Log in, a login page will be opened. In the login page, you will have the newly added button. We already added the redirection for this button.
After clicking on the login with github button, it will redirect you to authorization page. Here, it will ask you the authorize the login using the Github app. You have to authorize the permission.
Once, you will allow the authorization, it will redirecting back to the callback URL.
On the redirection to the callback URL, you will have the dashboard page.
Conclusion
Laravel 8 Socialite login with Github is managed by OAuth. This is a secure login if you don’t want your user to put email and password for the login. We implemented successfully the Github Login in Laravel 8. Hope, this tutorial will help you in creating a real and live application with the social login functionality.
rizky primadona says
nice, how about socialite laravel passport