Laravel Google login tutorial from scratch

In this tutorial, we will learn how to implement a user's login with google in Laravel 6 and Laravel 7 and save the user details like email, google auth id, username, name, etc in your database. For this tutorial, we will use Laravel official package socialite to implement the google login in Laravel.

1. Install and setup the Laravel project

Let's quickly install the fresh Laravel project. To install enter the following command

composer create-project laravel/laravel google-login --prefer-dist

2. Setup a database connection

Navigate to Laravel installed directory and rename .env.example file to .env. Now open the installed project in your code editor and paste the following code.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root

 Next, we will migrate the Laravel default two migration file user table and password_reset file. To do so, Enter the following command.

php artisan migrate

 The above command will create two table user and password_reset table.

3. Setup Laravel authentication scaffolding

By default, Laravel ships with default auth/login scaffolding. All you have to do is install the Laravel/UI package. To do so enter the following command.

composer require laravel/ui

The above command will install Laravel/UI package. I'll use bootstrap UI for the ready and go authentication. To create Laravel auth enter the following command.

php artisan ui bootstrap --auth

The above command will generate the login and register feature.

4. Install Socialite

Socialite is a official Laravel package that provides a simple way to authenticate using OAuth. To install the Socialite dependencies using composer enter the following command.

composer require laravel/socialite

5. Socialite Configuration

Once you are done with the installation of socialite. Update the service provider in config/app.php file.

// config/app.php

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

Service provider is the place for application bootstrapping meaning Laravel will make the socialite available to use. Next, Add the Socialite in the alias array.

// config/app.php

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

6. Create Google App

In order to implement Google auth in your Laravel application you need google app id and secret key. In this section we will be configuring google to get the access key and secret key. If you don't have google's auth credentials you can visit Google developers console. Below are the images that will help you to create app and get the google auth credentials.

Google developer console create credentials

Click create project and enter your project/website name

Once you fill all the fields click on create. Now click on Create Credentials and select OAuth client ID from the drop down

After clicking on OAuth client ID You will be asked to fill the basic info. 

Now fill the basic info and add your domain. Once you are done with it you will be asked to copy your secret key and id.

Now open your config/services.php file and paste the below code.

return [
    ....
    'google' => [
        'client_id' => 'app_id',
        'client_secret' => 'app_secret',
        'redirect' => 'http://localhost:8000/auth/google/callback',
    ],
]

Once you are done with the credentials setup. Now let's create a route for social auth. Copy and paste the below code in routes/web.php file

routes/web.php

Route::get('/google/redirect', 'SocialAuthController@redirect');
Route::get('/google/callback', 'SocialAuthController@callback');

7. Create a Controller

Use the below command to create a controller in Laravel using the terminal.

php artisan make:controller SocialAuthController

Now open your SocialAuthController and Copy & paste the below code.

<?php

namespace App\Http\Controllers;

use Socialite;
use Illuminate\Http\Request;
use App\Services\SocialAuthService;

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

    public function callback(SocialAuthService $service)
    {
    	$user = $service->createOrGetUser(Socialite::driver('google')->user());
    	auth()->login($user);

        return redirect()->to('/home');
    }
}

8. Create a migration and model for social auth

In this section, we will be creating a migration to map the user id and social auth id. Enter the below code to create a model and migration.

php artisan make:model SocialLogin -m

The above command will create a model and migration file. Now copy and paste the below code to update the migration file.

public function up()
{
    Schema::create('social_logins', function (Blueprint $table) {
        $table->integer('user_id');
        $table->string('provider_user_id');
        $table->string('provider');
        $table->timestamps();
    });
}

In the above code, we have added user_id, provider_user_id (google user-id), and provider which in this case will be google.

Now enter the below command to run the migration.

php artisan migrate

The above command will create a table social_logins in the database. Now open the App\SocialLogin.php file to set up the relationship between the user model and social login.

Copy and paste the below code to set up the relationship.

app/SocialLogin.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class SocialLogin extends Model
{
    protected $fillable = ['user_id', 'provider_user_id', 'provider'];

	public function user()
	{
	  return $this->belongsTo(User::class);
	}
}

In the above code, we have set up the relationship between the user model and the social login model. Now let's create a service class which will be responsible to handle the user and social login

9. Handling the user with service class

Create a file with the name SocialAuthService inside the app/services directory and copy & paste the below code.

app/Services/SocailAuthService.php

<?php

namespace App\Services;

use App\User;
use App\SocialLogin;
use Laravel\Socialite\Contracts\User as ProviderUser;

class SocialAuthService
{
    public function createOrGetUser(ProviderUser $providerUser)
    {
        $account = SocialLogin::whereProvider('google')
            ->whereProviderUserId($providerUser->getId())
            ->first();

        if ($account) {
            return $account->user;
        } else {

            $account = new SocialLogin([
                'provider_user_id' => $providerUser->getId(),
                'provider' => 'google'
            ]);

            $user = User::whereEmail($providerUser->getEmail())->first();

            if (!$user) {

                $user = User::create([
                    'email' => $providerUser->getEmail(),
                    'name' => $providerUser->getName(),
                    'password' => md5(rand(1, 9999)),
                ]);
            }

            $account->user()->associate($user);
            $account->save();

            return $user;
        }
    }
}

The above code will check if the user exists with the provided id. If not it will create a new user and associate the user the social auth provider id.

Now add the below code in your login/register blade file to test the google social auth login.

<a href="{{url('/google/redirect')}}" class="btn btn-primary">Login with Google</a>

10. Test the Social Auth Login

To test the social auth login. Open your browser and enter the http://localhost:8000/google/redirect.

 

Next: Laravel facebook social auth login