DEV Community

Cover image for Laravel 8 Login Using Google
shani singh
shani singh

Posted on

Laravel 8 Login Using Google

In this post i am going to explain about Authentication using Google, In this i am going to use Laravel Socialite Package.

You can read about Laravel Socialite Installation before going further in order to install socialite package.

STEP 1

Add Login with Google button in Login Form.

<a href="{{ route('google.login') }}" class="btn btn-google btn-user btn-block">
    <i class="fab fa-google fa-fw"></i> Login with Google
</a>
Enter fullscreen mode Exit fullscreen mode

STEP 2

Create Google Controller and google Login Function.

php artisan make:controller GoogleController
Enter fullscreen mode Exit fullscreen mode

Add Function in GoogleController

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Laravel\Socialite\Facades\Socialite;

class GoogleController extends Controller
{
    public function loginWithGoogle()
    {
        return Socialite::driver('google')->redirect();
    }

    public function callbackFromGoogle()
    {
        try {
            $user = Socialite::driver('google')->user();

            // Check Users Email If Already There
            $is_user = User::where('email', $user->getEmail())->first();
            if(!$is_user){

                $saveUser = User::updateOrCreate([
                    'google_id' => $user->getId(),
                ],[
                    'name' => $user->getName(),
                    'email' => $user->getEmail(),
                    'password' => Hash::make($user->getName().'@'.$user->getId())
                ]);
            }else{
                $saveUser = User::where('email',  $user->getEmail())->update([
                    'google_id' => $user->getId(),
                ]);
                $saveUser = User::where('email', $user->getEmail())->first();
            }


            Auth::loginUsingId($saveUser->id);

            return redirect()->route('home');
        } catch (\Throwable $th) {
            throw $th;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

STEP 3

Create Routes For Google,

// Google URL
Route::prefix('google')->name('google.')->group( function(){
    Route::get('login', [GoogleController::class, 'loginWithGoogle'])->name('login');
    Route::any('callback', [GoogleController::class, 'callbackFromGoogle'])->name('callback');
});
Enter fullscreen mode Exit fullscreen mode

STEP 4

Add Google Service in config/services.php File.

'google' => [
        'client_id' => '', //USE FROM Google DEVELOPER ACCOUNT
        'client_secret' => '', //USE FROM Google DEVELOPER ACCOUNT
        'redirect' => 'https://0a41-106-212-124-50.ngrok.io/google/callback/'
],
Enter fullscreen mode Exit fullscreen mode

STEP 5

Create Google Client ID & Secret from Google Developer's Account

After That Update in config/services.php File.

NOTE: Use NgRok To Host your App Locally and use same URL in Google Developer's Credentials.

STEP 6

Create Migration To Add google_id Column in Database.

php artisan make:migration add_google_id_in_users_table
Enter fullscreen mode Exit fullscreen mode

After That add Column in migration file.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddGoogleIdInUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('google_id')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('google_id');
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

STEP 7

Add google_id as fillable property in User Model.

protected $fillable = [
        'name',
        'email',
        'password',
        'status',
        'facebook_id',
        'google_id'
];
Enter fullscreen mode Exit fullscreen mode

All Set. Go To Login Page
The Output Result Will Look Like.
Login Page

If you get any issue while integrating it, do comment your problems.

Get Code on Techtool Github

You can watch this video I have explained this.

Thank You for Reading

Reach Out To me.
Twitter
Instagram
YouTube

Discussion (0)