Laravel 8 Login And Registration Example With Github

It is good to have a socialite login system in your application. Cause right now it is a trend to use socialite login systems like Facebook, Google, GitHub, Twitter, etc. In this tutorial, I am here to show you laravel 8 login system with Github.

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

Many websites, right now using this system. So we are going to show how we can create Laravel 8 GitHub login system. Let's build an Auth system on top of Laravel’s default Authentication to support login and signup Github.

 

laravel-socialite-example-from-scratch

Let's start laravel social login example tutorial.

Step 1 : Installation 

To get started with Socialite, use Composer to add the package to your project's dependencies:

composer require laravel/socialite

 

Step 2 : Configuration

Now add this into providers and aliases array in config/app.php file. 

config/app.php

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

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

 

Step 3 : Create Migration

Now let’s add some fields in our user’s migration provided by laravel to store avatar and provider info along with access_token. Add this to our default users table.

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');

        $table->string('avatar')->nullable();
        $table->string('provider', 20)->nullable();
        $table->string('provider_id')->nullable();
        $table->string('access_token')->nullable();

        $table->rememberToken();
        $table->timestamps();
    });
}

 

After this run the following command to complete our migration.

php artisan migrate

 

and open app/User.php model to add these fields in the fillable property so we can mass assign them later.

app/User.php

protected $fillable = [
     'name', 'email', 'password',
     'avatar', 'provider_id', 'provider',
     'access_token'
];

//You can also use below statement 

protected $guarded = ['*'];

 

Step 4 : Create Oauth App

Before using Socialite, you will also need to add credentials for the OAuth services your application utilizes. These credentials should be placed in your config/services.php configuration file.

And open your .env file and paste  client_id and client_secret for each provider.

GH_ID=your-github-app-id
GH_SECRET=your-github-app-secret

 

You can obtain credentials by visiting the following developer areas to set up all the providers in services.

Note : Make sure to set

APP_URL=http://localhost:8000

in .env file and it must match the providers redirect URL. Later in production you can change this to your actual app url. 

 

Visit providers website dev section and create Developer applications then fill the below details for each provider in config/services.php. For Github, you have to visit

 

 https://github.com/settings/developers

 

and after visiting here fill this input field like below.

login-with-github

And after getting your client_id and client_secret, open .env file and paste  client_id and client_secret for each provider and fill the below details for each provider in the config/services.php file.

To start just add Github first, if you can make one work-rest will be very easy, you just need client_id and secret for all the providers you wanted to support in config/services.php configuration file.

config/services.php

'github' => [
    'client_id'     => env('GH_ID'),
    'client_secret' => env('GH_SECRET'),
    'redirect'      => env('APP_URL') . '/oauth/github/callback',
]

 

Step 5 : Setup Route

We will need three routes, one for showing the list of buttons for providers, another for Redirect to the provider for authentication, and the last one to handle the callback from the provider once authorized.

routes/web.php

Route::get('auth/social', 'Auth\LoginController@show')->name('social.login');
Route::get('oauth/{driver}', 'Auth\LoginController@redirectToProvider')->name('social.oauth');
Route::get('oauth/{driver}/callback', 'Auth\LoginController@handleProviderCallback')->name('social.callback');

 

Step 6 : Setup Controller

Now visit your LoginController and add the following code.

app/Http/Controllers/Auth/LoginController.php

namespace App\Http\Controllers\Auth;

use App\User;
use Exception;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{

    public function __construct()
    {
        $this->middleware('guest');
    }

    protected $providers = [
        'github','facebook','google','twitter'
    ];

    public function show()
    {
        return view('auth.login');
    }

    public function redirectToProvider($driver)
    {
        if( ! $this->isProviderAllowed($driver) ) {
            return $this->sendFailedResponse("{$driver} is not currently supported");
        }

        try {
            return Socialite::driver($driver)->redirect();
        } catch (Exception $e) {
            // You should show something simple fail message
            return $this->sendFailedResponse($e->getMessage());
        }
    }

  
    public function handleProviderCallback( $driver )
    {
        try {
            $user = Socialite::driver($driver)->user();
        } catch (Exception $e) {
            return $this->sendFailedResponse($e->getMessage());
        }

        // check for email in returned user
        return empty( $user->email )
            ? $this->sendFailedResponse("No email id returned from {$driver} provider.")
            : $this->loginOrCreateAccount($user, $driver);
    }

    protected function sendSuccessResponse()
    {
        return redirect()->intended('home');
    }

    protected function sendFailedResponse($msg = null)
    {
        return redirect()->route('social.login')
            ->withErrors(['msg' => $msg ?: 'Unable to login, try with another provider to login.']);
    }

    protected function loginOrCreateAccount($providerUser, $driver)
    {
        // check for already has account
        $user = User::where('email', $providerUser->getEmail())->first();

        // if user already found
        if( $user ) {
            // update the avatar and provider that might have changed
            $user->update([
                'avatar' => $providerUser->avatar,
                'provider' => $driver,
                'provider_id' => $providerUser->id,
                'access_token' => $providerUser->token
            ]);
        } else {
            // create a new user
            $user = User::create([
                'name' => $providerUser->getName(),
                'email' => $providerUser->getEmail(),
                'avatar' => $providerUser->getAvatar(),
                'provider' => $driver,
                'provider_id' => $providerUser->getId(),
                'access_token' => $providerUser->token,
                // user can use reset password to create a password
                'password' => ''
            ]);
        }

        // login the user
        Auth::login($user, true);

        return $this->sendSuccessResponse();
    }

    private function isProviderAllowed($driver)
    {
        return in_array($driver, $this->providers) && config()->has("services.{$driver}");
    }
}

 

Now let's create the view for the login screen.

 

Step 7 : Create Blade File

 

Create our blade file to show login button. To create login button for corresponding socialite system. Just paste this below code to you resources/views/auth/login.php file.

 

Read more : Captcha Code and Validation Example using Botdetect Package in Laravel

 

resources/views/auth/login.php

 

Now visit this below URL 

 

URL
 http://localhost:8000/login

 

To check whether it works or not. Hope it can help you and it will work for your application. 

 

#laravel #laravel-8x #laravel-socialite