Google Login in Laravel Using Laravel Socialite

Recently I have published an article Login with LinkedIn Using Laravel Socialite and one of our readers asked about integrating Google Login in Laravel. Google sign-in is also one of the popular platforms used for social login on the website.

When you allow users to login with their social profile on your website, you skip the process of validating their email. Your users don’t need to follow an email activation process. We can rely on social sites as they already validated users on their platform. It gives a better user experience for your users as they don’t need to remember their login credentials for your website and also saves you from adding the codes for verification flow. It’s a win-win situation.

In this article, we study step by step guide on adding Google Login in Laravel using Laravel Socialite. Laravel socialite handles OAuth flow for social login behind the scenes. This package speeds up the process of integrating social login on Laravel.

For this tutorial, I’ll use a fresh Laravel installation so run the below command which will install Laravel for you:

composer create-project --prefer-dist laravel/laravel googlelogin

Upon Laravel installation, create a database and add your database credentials in the .env file. As we are adding social login in the application, I will add 2 more columns to the default user migration file and modified it’s code little bit.

Open your user’s migration file and add the code below to the up method.

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->nullable();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password')->nullable();
        $table->string('provider');
        $table->string('provider_id');
        $table->rememberToken();
        $table->timestamps();
    });
}

In the above code I have added 2 columns provider and provider_id which will hold the values ‘google’ and user’s Google profile id respectively. Create the ‘users’ table by running the migrate command.

php artisan migrate

You also need to add these 2 columns to the User model.

app/User.php

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password', 'provider', 'provider_id',
];

Create Google Application and Get Your Credentials

Next, we need to create a project on the Google APIs console. We will require client id and client secret of the application to complete the OAuth process for the users.

Follow the steps below for creating a Google project and get the credentials. For the sake of the tutorial, I am using the local server URL. You can adjust this URL as per your requirement.

  • Go to the Google Developer Console.
  • Click on the drop-down and create a new project by clicking on (+) sign. Alternately, you can also select the existing project.
  • On the project dashboard select Credentials from the sidebar.
  • Under the Credentials tab, click on the Create credentials drop-down and select OAuth client ID.
  • Select the Web application from the Application type. In the Authorized redirect URLs enter the URL http://localhost:8000/google/callback.

Once you save it, you will get the popup along with your Client ID and Client Secret. Copy these keys which we will require in few moments.

Create Routes and Controller

You are ready with your API keys. Now to proceed further we have to create routes, blade file, and controller. Create a LoginController using the command:

php artisan make:controller LoginController

After this, create a blade file called login.blade.php and add the below HTML to it.

<a href="{{ url('/login/google') }}">
    {{ __('Login with Google') }}
</a>

Call this view from the index method of LoginController.

public function index()
{
    return view('login');
}

For calling this view, you need to add a route for it. Let’s add a few more routes also which will require for the next part of the tutorial.

Route::get('login', 'LoginController@index');
Route::get('login/{provider}', 'LoginController@redirectToProvider');
Route::get('{provider}/callback', 'LoginController@handleProviderCallback');
Route::get('/home', function () {
    return 'User is logged in';
});

Notice that I added a home route. When a user will login with Google, I will redirect them to the home route. I just keep it for demo purposes. You should change this route to something else.

Google Login in Laravel Using Laravel Socialite

So far we are done with the basic setup required for social login. Now. it’s time to install the Laravel Socialite library. Install it by running the below command in the terminal.

composer require laravel/socialite

Upon installation of library, open the config/services.php and add Google configuration as follows:

'google' => [
    'client_id'     => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect'      => env('GOOGLE_REDIRECT_URL'),
],

As we used env method to get credentials, we need add these credentials in the .env file.

GOOGLE_CLIENT_ID=YOUR_CLIENT_ID
GOOGLE_CLIENT_SECRET=YOUR_CLIENT_SECRET
GOOGLE_REDIRECT_URL=http://localhost:8000/google/callback

Make sure to replace the placeholders with actual values. Finally, we need to add code in LoginController.php file which redirects user to the Google login page and in return handles the response. In this file, we are writing a function that redirects a user to the Google login page and on successful authorization, it will insert user details in the database and log the user in.

LoginController.php

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Socialite;
use App\Models\User;
use Auth;
 
class LoginController extends Controller
{
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';
 
    /**
     * Call the view
     */
    public function index()
    {
        return view('login');
    }
 
    /**
     * Redirect the user to the Google authentication page.
     *
     * @return Response
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }
   
    /**
     * Obtain the user information from Google.
     *
     * @return Response
     */
    public function handleProviderCallback($provider)
    {
        $user = Socialite::driver($provider)->user();
        $authUser = $this->findOrCreateUser($user, $provider);
        Auth::login($authUser, true);
        return redirect($this->redirectTo);
    }
   
    /**
     * If a user has registered before using social auth, return the user
     * else, create a new user object.
     * @param  $user Socialite user object
     * @param $provider Social auth provider
     * @return  User
     */
    public function findOrCreateUser($user, $provider)
    {
        $authUser = User::where('provider_id', $user->id)->first();
        if ($authUser) {
            return $authUser;
        }
        return User::create([
            'name'     => $user->name,
            'email'    => $user->email,
            'provider' => $provider,
            'provider_id' => $user->id
        ]);
    }
}

In our controller file, we are checking if the user with provider_id exists already or not. If it exists then return the current user instance else insert it in the users table and log the user in.

I hope you got to know about Google Login in Laravel using Socialite package. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

2 thoughts on “Google Login in Laravel Using Laravel Socialite

  1. Stuck on same issue 🙁

    Socialite: InvalidStateException in AbstractProvider.php

    Laravel \ Socialite \ Two \ InvalidStateException

    C:\wamp64\www\laravel-dev\vendor\laravel\socialite\src\Two\AbstractProvider.php

Leave a Reply

Your email address will not be published. Required fields are marked *