Laravel 8 Login with Google Account Example

Share Me
  •  
  •  
  •  
  • 3
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    3
    Shares
Laravel 8 Login with Google Account

Hello Dev’s Hope all are you okay. Today in this example, I will give you a short and simple example of how to login with any google account in laravel 8 application. Now we will use here laravel socialite package for login with our Google account in our laravel 8 application. Here we know Laravel 8 Login with Google Account.

Nowadays most of user mostly wants to sign up or login with social network, because it’s easy and also time consuming.

So by use of social login in our application it will make our application is more user friendly.

So for this just need to follow below step to use social authentication in our laravel 8 application:

Install Laravel 6

Now we will create a new laravel 8 fresh application.

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

Install Socialite

Now in this step we will install our Socialite Package that provide our fb api to connect with google account. So, at first open our terminal and run bellow command.

composer require laravel/socialite

config/app.php

After that install above package we should add new providers and aliases in our config file.

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

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

Install Auth

Now first of we need to install laravel/ui package as like bellow:

composer require laravel/ui

We can use by following commands for creating auth:

php artisan ui bootstrap --auth

Now we need to run npm command, otherwise we can not see it better layout of login and register page.

Install NPM:

npm install

Run NPM:

npm run dev

Create Google App

Now in this step we need to create a google client id and also a secret that way we can get all information of other user. so if we don’t have google app account then we can create from here : Google Developers Console. we can find bellow screen :

Laravel 8 Login with Google Account

So now we have to click on Credentials and also need to choose second option oAuth client id and also click Create new Client ID button. now we can see following slide:

Laravel 8 Login with Google Account

After that create account we can copy client id and also secret.

config/services.php

We will create the index.php file in the views directory.

    ....
    'google' => [
        'client_id' => 'app id',
        'client_secret' => 'add secret',
        'redirect' => 'http://learnl52.hd/auth/google/callback',
    ],
]

Add Database Column

Now in this step first we need to create a migration for add google_id in our user table. So let’s run bellow command:

php artisan make:migration add_google_id_column
<php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
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()
    {
        //
    }
}

app/User.php

Now need to update mode like this way:

<php
namespace App;
  
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
  
class User extends Authenticatable
{
    use Notifiable;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'google_id'
    ];
  
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
   
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Create Routes

Now after the adding google_id column at first we have to add a new route for google login. so let’s add bellow route in routes.php file.

app/Http/routes.php

Route::get('google', function () {
    return view('googleAuth');
});
    
Route::get('auth/google', 'Auth\LoginController@redirectToGoogle');
Route::get('auth/google/callback', 'Auth\LoginController@handleGoogleCallback');

Update Controller File

After add new route,then we need to add method of google auth that method will handle google callback url and etc, first put bellow code on our LoginController.php file.

app/Http/Controllers/Auth/LoginController.php

<php
namespace App\Http\Controllers\Auth;
   
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Socialite;
use Auth;
use Exception;
use App\User;
   
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
   
    use AuthenticatesUsers;
   
    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';
   
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
   
    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 return redirect('/home');
   
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id'=> $user->id
                ]);
  
                Auth::login($newUser);
   
                return redirect()->back();
            }
  
        } catch (Exception $e) {
            return redirect('auth/google');
        }
    }
}

Create Blade File

Ok that’s good, now we are at last here we need to add blade view so first create new file googleAuth.blade.php file and also put bellow code:

resources/views/googleAuth.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 6 Login with Google Account Example</title>
</head>
<body>
    <div class="container">
       <div class="row">
         <div class="col-md-12 row-block">
          <a href="{{ url('auth/google') }}" class="btn btn-lg btn-primary btn-block">
          <strong>Login With Google</strong>
          </a> 
         </div>
       </div>
    </div>
</body>
</html>

Read Also : How to run laravel project without php artisan serve command ?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →