DEV Community

Rohit Urane
Rohit Urane

Posted on

6 3

How to Implement login with google in laravel

Image description

Nowadays, users are less interact with the website. You want to register users on your platform. You should simplify the process of registration and login for your application. Laravel provides a socialite package to ease the process, i.e., in minimum steps, users can connect to your application. In this article, we implement login with google in laravel application.

Step-by-step guide on google login in the laravel application

  1. Install Package Install Socialite package on laravel application. Run the following command.
composer require laravel/socialite
Enter fullscreen mode Exit fullscreen mode
  1. Configure credentials See the Screenshot for getting google credentials. Click here to make credentials on the google platform.

You can add credentials to the env file and add the environment variable on a config/services.php file against the google variable like below:

GOOGLE_AUTH_CLIENT_ID=XXXXXXXXXXXXXXXX
GOOGLE_AUTH_CLIENT_SECRET=XXXXXXXXXXXXX
GOOGLE_AUTH_URL=http://127.0.0.1:8000/auth/google
Enter fullscreen mode Exit fullscreen mode

The services.php file looks like the below:

'google'=>[
    'client_id' => env('GOOGLE_AUTH_CLIENT_ID'),
    'client_secret' => env('GOOGLE_AUTH_CLIENT_SECRET'),
    'redirect'=> env('GOOGLE_AUTH_URL')
]
Enter fullscreen mode Exit fullscreen mode
  1. Make migration column to the user table Make a migration file that will create a column inside the user's table. Run migration command in your application.
<?php

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

class AddGoogleIdColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {

            $table->string('google_id')->nullable();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropColumns('google_id');
    }
}
Enter fullscreen mode Exit fullscreen mode

Add google_id field to fillable property on User.php file.

protected $fillable = [
    'name',
    'email',
    'password',
    'google_id'
];
Enter fullscreen mode Exit fullscreen mode
  1. Create a controller for social login You can make a controller for social login and load the drivers for social login. I am going to load google driver.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use Inertia\Inertia;
use Illuminate\Support\Facades\Route;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class SocialController extends Controller
{
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }
    public function handleGoogleCallback()
    {
        try {
            $user = Socialite::driver('google')->user();
            $finduser = User::where('google_id', $user->id)->first();
            if($finduser){
                Auth::login($finduser);
                return redirect('/');
            }else{
                $checkUser = User::where('email', $user->email)->first();
                if($checkUser) {
                    $checkUser->google_id = $user->id;
                    $checkUser->save();
                    Auth::login($checkUser);
                } else {
                    $newUser = User::create([
                        'name' => $user->name,
                        'email' => $user->email,
                        'google_id'=> $user->id,
                        'password' => encrypt('123456dummy')
                    ]);
                    Auth::login($newUser);
                }
                return redirect('/');
            }
        } catch (Exception $e) {
            return Inertia::render('Auth/Login', [
                'canResetPassword' => Route::has('password.request'),
                'status' => 'Something Went wrong!! Try later',
            ]);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Click Here

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
gbhorwood profile image
grant horwood

i wrote up how to do it with the google sdk, in case anyone is interested in doing it the unnecessarily difficult way.

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay