Create Login With Google OAuth Using Laravel Socialite
Tags: php, laravel, oauth, authentication
Published: 2023-01-20 00:05:35

---
title: Create Login With Google OAuth Using Laravel Socialite
published: true
date: 2022-08-18 11:12:08 UTC
tags: 
- PHP
- Laravel
- OAuth
- Authentication
canonical_url: https://fajarwz.com/blog/create-login-with-google-oauth-using-laravel-socialite/
---

![Google illustration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/proynsov3hwwci5aupzh.png)

For some webs, authentication is one of the most important thing. And maybe sometimes our websites also need to easily gain more engagement by eliminating a bit hassle by letting users login to the web easily using their other platform account.

Google is one of the most widely used platform by people around the globe. This can be used as our advantage if we can provide a one-click login feature by using Google account, without making users to fill data manually that can be take about 5 minutes before they can use our website.

There is a technology called [OAuth (Open Authorization)](https://oauth.net/), it is an open standard for access delegation. With OAuth we can login to websites or applications using other website or application account without giving or creating new passwords. This can make granting access to our website easier and more secure for user rather than to create an account on our website.

Laravel provides a package to authenticate with OAuth providers using [Laravel Socialite](https://laravel.com/docs/9.x/socialite). Currently Socialite supports authentication via some well-known platform like Facebook, Twitter, LinkedIn, Google, GitHub, GitLab, and Bitbucket.

This time I will share about how we can make Google OAuth login using Laravel Socialite.

## Installation
### Laravel Installation
First you want to install a Laravel app first.

```
composer create-project laravel/laravel blog-google-oauth-laravel-socialite
```

### Laravel Socialite Installation
Get started with Socialite by adding the package using Composer package manager.

```
composer require laravel/socialite
```

## Configuration
Typically we need credentials for OAuth providers we use. For Google, we need to have `GOOGLE_CLIENT_ID`
and `GOOGLE_CLIENT_SECRET` for our web. We can get those credentials by creating Google API Credentials in Google APIs Console.

### Create Google API Credentials

#### Step 1: Open the Credentials Page
By visiting [Google APIs console](https://console.developers.google.com/apis). This is how the page looks when this article is written. 

![Google API console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ax6qtfpr040shqnwv9c1.png)

#### Step 2: Create a Project
Click the dropdown that circled above, and then click "New Project"

![Projects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vnr10u9z0nqx14h48m7g.jpg)

Fill the detail about your project, here is the example and then click "Create".

![Create project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q0k2vcigsqs9ha1zl2j4.png)

Wait until project successfully created

![Project created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qdixb10srme4ai26o59a.jpg)

#### Step 3: Switch to the Project
Switch to our newly project by clicking the droprown of project that is displayed in the navbar above, click the project and click "Open" button.

![Switch project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39k8dkfgg128518olltj.png)

#### Step 4: Try to Create OAuth Client ID Credential
Create the credential by choosing "Credentials" in the side bar, click "Create Credentials" button and choose "OAuth Client ID".

![Create credentials](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a9rco7nvzgrct1660rys.png)

#### Step 5: Configure Consent Screen
If it says we need to configure consent screen first then click the button

![Configure consent screen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/95o5qk0p06kaduxv7gfr.png)

We will be redirected to the screen and choose based on your needs, here I will choose "External" option then create.

![Internal or external](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8i55psmo1qk7axyxq9oy.png)

#### Step 6: Edit App Registration
Fill the form with. Here I just fill the App Name, user support email, and developer contact information, and then click "Save and Continue".

![App registration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w503oa4exovxh3tm2yhf.png)

You can continue to fill the form but in our simple app it's not necessary. I proceed to Credentials page and try to "Create OAuth Client ID" once again.

![Create credentials](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9f1ikipe5r5td4t3zqxq.png)

#### Step 7: Create OAuth Client ID Credential
Here we can fill the detail about our app and fill the authorised redirect URIs. This is the URI that we will use to redirect user after they choose their Google account to login to our web. For example here I use `http://127.0.0.1:8000/callback/google` for the callback URI.

![Create OAuth](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mogeaa1ng8a77yvannmd.png)

#### Step 8: OAuth Client Created
Now we get the Client ID and the Client Secret. 

![OAuth created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b57iya18jzjg1rew5fw5.png)

### Configuration with Laravel

#### Step 1: Place the Credentials in .env

Place the Client ID and Client Secret key we got just now in `GOOGLE_CLIENT_ID` key and `GOOGLE_CLIENT_SECRET` key in the Laravel `.env` respectively. Another key to add in `.env` is `GOOGLE_REDIRECT`, fill it with our callback URI we use in the Google API Console.

```
GOOGLE_CLIENT_ID=blabla.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=BLA-BLA-BLA
GOOGLE_REDIRECT=http://127.0.0.1:8000/callback/google
```

#### Step 2: Place the Google .env key in config/services.php

The credentials should be placed in our `config/services.php` configuration file of Laravel.

```php
// config/services.php

return [
//...
    'google' => [
        'client_id'     => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect'      => env('GOOGLE_REDIRECT')
    ],
];
```

> **Read also:** 
> [https://fajarwz.com/blog/laravel-api-documentation-generator-with-open-api-swagger-using-darkaonline-l5-swagger/](Laravel Api Documentation Generator With OpenAPI/Swagger Using DarkaOnLine/L5-Swagger)

### Database Configuration

#### Step 1: Create the Migration

Create two columns named `social_id` and `social_type` in `users` table. We can add to the `users` table migration or add a migration for adding both columns

```
php artisan make:migration "add social id and social type field to users table"
```

Add these codes to the new migration file

```php
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {    // add the below column to "users" table
            $table->string('social_id')->nullable();    // add social_id column with varchar type
            $table->string('social_type')->nullable();  // add social_type column with varchar type
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('social_id');
            $table->dropColumn('social_type');
        });
    }
};
```

#### Step 2: Add social_id and social_type to $fillable in User Model

Add these values to `$fillable`.

```php
// app\Models\User.php

protected $fillable = [
    'name',
    'email',
    'password',
    'social_id',
    'social_type'
];
```

#### Step 3: Migrate the Database Migration

Create the `blog_google_auth_laravel_socialite` database or your preferred database name for this Laravel app.

```
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog_google_auth_laravel_socialite
DB_USERNAME=root
DB_PASSWORD=
```

Then run the database migration command.

```
php artisan migrate
```

## Integration with Authentication Feature

We will use [Laravel Breeze](https://laravel.com/docs/9.x/starter-kits#laravel-breeze) as an example of our existing authentication implementation.

### Install Laravel Breeze

#### Step 1: Install Laravel Breeze Package

Install it with the following command:

```
composer require laravel/breeze --dev
```

#### Step 2: Install the Laravel Breeze Blade Stack

Here I will use the Blade stack for Laravel Breeze so I will run the following command:

```
php artisan breeze:install
```

#### Step 3: Run the NPM Command

We need to run the `npm install` and then `npm run dev` command.

```
npm install
npm run dev
```

#### Step 4: Run Our Laravel Web

Run the local development server in another terminal

```
php artisan serve
```

Our web can be visited in `http://127.0.0.1:8000`

#### Step 5: Check the Authentication Feature

Check the home, login, and dashboard page.

![Laravel home](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lqjk35fiz9132pol5qgv.png)

To login to dashboard we need to create an account first, we can create it in register page.

![Register](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t1y15iaqxcr653s7vli3.png)

This is how the Dashboard page looks

![Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69vxt29k0ya9gtavh5de.png)

Click the name with dropdown in the navbar and click "Logout" to logout from the web.

### Create the Login With Google Button and Implement it

We will start creating the "login with Google" feature.

#### Step 1: Create the "Redirect to Google" and callback Function in Our Controller

First create the function in another controller. Here I create the controller named `GoogleSocialiteController.php`.

```
php artisan make:controller Auth/GoogleSocialiteController
```

Create the function below:

```php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Auth;
use Exception;
use Socialite;

class GoogleSocialiteController extends Controller
{
    public function redirectToGoogle()
    {
        // redirect user to "login with Google account" page
        return Socialite::driver('google')->redirect();
    }

    public function handleCallback()
    {
        try {
            // get user data from Google
            $user = Socialite::driver('google')->user();

            // find user in the database where the social id is the same with the id provided by Google
            $finduser = User::where('social_id', $user->id)->first();

            if ($finduser)  // if user found then do this
            {
                // Log the user in
                Auth::login($finduser);

                // redirect user to dashboard page
                return redirect('/dashboard');
            }
            else
            {
                // if user not found then this is the first time he/she try to login with Google account
                // create user data with their Google account data
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'social_id' => $user->id,
                    'social_type' => 'google',  // the social login is using google
                    'password' => bcrypt('my-google'),  // fill password by whatever pattern you choose
                ]);

                Auth::login($newUser);

                return redirect('/dashboard');
            }

        }
        catch (Exception $e)
        {
            dd($e->getMessage());
        }
    }
}

```

#### Step 2: Create the routes

Add the routes below:

```php
use App\Http\Controllers\Auth\GoogleSocialiteController;

Route::get('auth/google', [GoogleSocialiteController::class, 'redirectToGoogle']);  // redirect to google login
Route::get('callback/google', [GoogleSocialiteController::class, 'handleCallback']);    // callback route after google account chosen
```

#### Step 3: Create the "Login With Google" button

Create the button in the login view. The view can be found in `resources/views/auth/login.blade.php`.

```php
// resources/views/auth/login.blade.php

<a href="{{ url('auth/google') }}" class="bg-blue-600 text-white rounded-md px-4 py-2 ml-2">
    Google Login
</a> 
```

![Google login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3medw333h5crg7f16jzi.png)

## Test It

When the button clicked it will redirect to Google account options

![Redirect google](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m6tq2s9d7gkmkbc6dep9.jpg)

After we choose an account, it will redirect to our web `/dashboard`.

![Redirect dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wce9oynh15uugyuocsaf.jpg)

When we check at our `users` table, we found our email registered and the `social_id` filled

![Users table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ge1lprcpns2p90ekd5ml.jpg)

## Conclusions
That’s it. We have successfully build an authentication feature with login with Google option. Here we use [laravel/socialite](https://laravel.com/docs/9.x/socialite) package, integrate it with our database, create a controller, create the endpoints, create the button, and done.

A repo for this example case can be found here [fajarwz/blog-google-oauth-laravel-socialite](https://github.com/fajarwz/blog-google-oauth-laravel-socialite).

## Reference
[Laravel Socialite - Laravel](https://laravel.com/docs/9.x/socialite)

## Read Also
[Laravel Rest API Authentication Using JWT Tutorial](https://fajarwz.com/blog/laravel-rest-api-authentication-using-jwt-tutorial/)