Laravel 8 Login Using Google
Tags: laravel, php, programming, tutorial
Published: 2021-08-29 11:23:55

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](https://dev.to/shanisingh03/how-to-login-with-facebook-in-laravel-124e) before going further in order to install socialite package.

### STEP 1

Add Login with Google button in Login Form.

```php
<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>
```

### STEP 2

Create Google Controller and google Login Function.

```php
php artisan make:controller GoogleController
```

Add Function in GoogleController
```php
<?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;
        }
    }
}

```

### STEP 3

Create Routes For Google,

```php
// 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');
});
```

### STEP 4

Add Google Service in `config/services.php` File.

```php
'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/'
],
```

### STEP 5 

Create Google Client ID & Secret from [Google Developer's Account](https://console.cloud.google.com/apis/credentials)

After That Update in `config/services.php` File.

### NOTE: Use [NgRok](https://ngrok.com/) 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
php artisan make:migration add_google_id_in_users_table
```

After That add Column in migration file.

```php
<?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');
        });
    }
}
```

### STEP 7
Add `google_id` as fillable property in User Model.

```php
protected $fillable = [
        'name',
        'email',
        'password',
        'status',
        'facebook_id',
        'google_id'
];
```
All Set. Go To Login Page 
The Output Result Will Look Like.
![Login Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hyibpuxkcbflcqh1a9k7.png)

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

Get Code on [Techtool Github](https://github.com/TechTool-India/ExampleProject/tree/social-login)

You can watch this video I have explained this.

{% youtube Ojvg231fV6A %}


Thank You for Reading

Reach Out To me.
[Twitter](https://twitter.com/shanisingh03)
[Instagram](https://www.instagram.com/shanisingh03/)
[YouTube](https://www.youtube.com/channel/UCOy6o08Yn9DtXMKqxhD9ivA)