Login with Google in Laravel 5.8 App using Socialite Package

Login with Google in Laravel 5.8 App using Socialite Package

In this tutorial, i would like to share with you how to login with google account using socialite package in laravel 5.8 app. we can easily sign in and signup with google gmail account in laravel 5.8. we will use google authentication for login in laravel 5.8.

In this tutorial, i would like to share with you how to login with google account using socialite package in laravel 5.8 app. we can easily sign in and signup with google gmail account in laravel 5.8. we will use google authentication for login in laravel 5.8.

If you want to create login with google account then you can do it easily using laravel socialite composer package. If you use other php framework then it difficult to make login with google. But Laravel provide socialite so you can so it quickly. You just need to create secret, app id from google api console.

Just follow few steps to done login with google account example:

Step 1: Install Laravel 5.8

In this step, if you haven't laravel 5.8 application setup then we have to get fresh laravel 5.8 application. So run bellow command and get clean fresh laravel 5.8 application.

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

Step 2: Install Socialite Package

In first step we will install Socialite Package that provide fb api to connect with google account. So, first open your terminal and run bellow command:

composer require laravel/socialite

After install above package we should add providers and aliases in config file, Now open config/app.php file and add service provider and aliase

'providers' => [

    ....

    Laravel\Socialite\SocialiteServiceProvider::class,

],

'aliases' => [

    ....

    'Socialite' => Laravel\Socialite\Facades\Socialite::class,

],

Step 3: Create Google App

In this step we need google client id and secret that way we can get information of other user. so if you don't have google app account then you can create from here : Google Developers Console. you can find bellow screen :

Login with Google in Laravel 5.8 App using Socialite Package

Now you have to click on Credentials and choose first option oAuth and click Create new Client ID button. now you can see following slide:

Login with Google in Laravel 5.8 App using Socialite Package

after create account you can copy client id and secret.

Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way:

config/services.php

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

Step 4: Add Database Column

In this step first we have to create migration for add google_id in your user table. So let's run bellow command:

php artisan make:migration add_google_id_column

Migration

<?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()
    {
        //
    }
}

Update mode like this way:

app/User.php

<?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',
    ];
}

Step 5: Create Routes

After adding google_id column first we have to add 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\[email protected]');
Route::get('auth/google/callback', 'Auth\[email protected]');

Step 6: Update Controller File

After add route, we need to add method of google auth that method will handle google callback url and etc, first put bellow code on your 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');
        }
    }
}

Step 7: Create Blade File

Ok, now at last we need to add blade view so first create new file googleAuth.blade.php file and put bellow code:

resources/views/googleAuth.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 5.8 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>

Ok, now you are ready to use open your browser and check here : URL + '/google'.

I hope it can help you...

laravel php

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Php how to delete multiple rows through checkbox using ajax in laravel

In this article i will let you know to delete multiple rows through checkbox using ajax in laravel and before delete we will give a confirmation message.

5 Laravel’s Hidden Gems

Spread the love1. Stop on first validation error By default, Laravel will check for all validation rules and return a list of errors. But if you want to stop this process after first validation failure, that’s how you can achieve…Read More→

Some of the most frequent how tos in Laravel

Spread the loveHow to get relationship from relationship using With() in Laravel Some times there are cases where you want to get relationship from relationship in Laravel, that can be achieved via following: How to create multiple where clauses in…Read More→

10 Laravel Quick Tips

Spread the loveTip 1. Controllers Having Single Action In some situations you need a single action in a controller, if this is the case in Laravel you can achieve it by __invoke() method. Routes: Artisan command to generate this controller:…Read More→

How to Install Laravel PHP Framework with Nginx on Ubuntu 20.04

Laravel is the most popular, free, and open-source PHP framework in the world, known for its expressive and elegant syntax. Laravel is accessible, powerful, and offers some of the best web development tools required for large, robust, and modern applications. In this article, you will learn how to install the Laravel PHP Framework on Ubuntu 20.04 server running on the Nginx web server.