Skip to main content

Add Login with Google to your Laravel project using socialite

Laravel Social_login with google:
In this tutorial we’re going to add authentication via Google to a Laravel app. We’re going to use Socialite and start from scratch.

1. Create Laravel app 

Create a new laravel app with a database and get everything up and running.
Click here for a guide on how to create a Laravel app from scratch 

2. Install Socialite 

Install socialite by running the following command on the command line. 
composer require laravel/socialite

If you want to learn more about socialite  click here.

3. Configure Laravel 

Once you have your project up and running, it is time to start our project.
First add credentials to config/services.php. Socialite supports Facebook, Twitter, LinkedIn, Google, GitHub and Bitbucket. Other providers require packages from the community, which are all listed here.
These providers follow the OAuth 2.0 spec and therefore require a client_id, client_secret and redirect url. We’ll obtain these in the next step! First, add the values to the config file because socialite will be looking for them when we ask it to.
'google' => [
  'client_id'     => env('GOOGLE_CLIENT_ID'),
  'client_secret' => env('GOOGLE_CLIENT_SECRET'),
  'redirect'      => env('GOOGLE_REDIRECT')
],
Since we added a new package, make sure to add to the service providers array in config/app.php:
/*
* Package Service Providers...
*/

Laravel\Socialite\SocialiteServiceProvider::class,
Service Providers are the central place for application bootstrapping. The above line let’s Laravel to know to make the Socialite available for use.
Add an alias to Socialite so it is easier to reference later, also in config/app.php file:
'aliases' => [
  // ...
  'Socialite' => Laravel\Socialite\Facades\Socialite::class,
]

4. Create the basic authentication scaffold 

php artisan make:auth
This will create a user model and some views for register and login pages. 
If you get an error of  “command does not exist” (depending on your version of laravel).
You can try using this instead:
composer require laravel/ui php artisan ui vue --auth php artisan migrate
Then run:
composer update

You can change vue with react if you use React in your project (see Using React).
And then you need to perform the migrations and compile the frontend
php artisan migrate npm install && npm run dev

5. Create your app in Google 

Select OAuth client ID > Consent > Web application
A modal will pop up with your apps client id and client secret. Add these values to your .env file.
GOOGLE_CLIENT_ID=000000000000-XXXXXXXXXXX.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=XXXXXXXXXXXXX
GOOGLE_REDIRECT=http://localhost:8000/callback

Add the callback url. The user will be redirected back to this endpoint.

6. Handle your routes 

Head into routes/web.php and add endpoints for redirect and callback:
Route::get('/redirect', 'Auth\LoginController@redirectToProvider');
Route::get('/callback', 'Auth\LoginController@handleProviderCallback');

Go to app/http/auth/LoginController.php  or any other controller of your choice and paste the two  following methods.
The first method redirectToProvider()  will show the Google authentication page in the same window where the user is viewing your webpage (no annoying pop ups):
The next handleProviderCallback() method will handle after a successful Google authentication:

      public function redirectToProvider()

    {
        return Socialite::driver('google')->redirect();
      
    
           }
        /**
         * Obtain the user information from Google.
         *
         * @return \Illuminate\Http\Response
         */
    
     public function handleProviderCallback()
    {
             try {
            $user = Socialite::driver('google')->user();
        } catch (\Exception $e) {
            return redirect('/login');
            
        }

        // check if they're an existing user
        $existingUser = User::where('email', $user->email)->first();
        log::info('callback here 2');
        if ($existingUser) {
            // log them in
           
            auth()->login($existingUser, true);
        } else {
           // create a new user
            $newUser                  = new User;
            $newUser->name            = $user->name;
            $newUser->email           = $user->email;
            $newUser->google_id       = $user->id;
            $newUser->avatar          = $user->avatar;
            $newUser->avatar_original = $user->avatar_original;
            $newUser->save();
            auth()->login($newUser, true);
        }
        return redirect()->to('/home');
    }
Right now this will authenticate the user and dump the info we get back on the screen. If you run this you can see we get a token, refreshToken, name, email, avatar, user object, avatar and avatar_original field.
NOTE: if you haven't already,  make sure you have specified the necessary classes at the top of the page.   
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Log;
use App\User;
use Socialite;

7. Update the users table migration 

Update your create_users_table migration to include these new fields. You could alternatively create a new migration for adding theses columns, which would be good for an existing app:
<?php

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

class CreateUsersTable extends Migration
{
  /**
    * Run the migrations.
    *
    * @return void
    */
  public function up()
  {
      Schema::create('users', function (Blueprint $table) {
          $table->increments('id');
          $table->string('name');
          $table->string('google_id');
          $table->string('email')->unique();
          $table->string('password')->nullable();
          $table->string('avatar')->nullable();
          $table->string('avatar_original')->nullable();
          $table->rememberToken();
          $table->timestamps();
      });
  }

  /**
    * Reverse the migrations.
    *
    * @return void
    */
  public function down()
  {
      Schema::dropIfExists('users');
  }
}
Run your project with php artisan serve and make sure everything works
Congrats! 


Comments

Popular posts from this blog

Personality Profile #1 | George Boole

Boole and the Algebra of Logic: George Boole (1815–1864) was a British mathematician and he’s considered to be the inventor of The algebra of logic, which is a system showing the underlying mathematical structure of logic. Boole proposed that logical propositions should be expressed as algebraic equations. The algebraic manipulation of the symbols in the equations provides a fail-safe method of logical deduction, i.e. logic can be reduced to algebra. He replaced the operation of multiplication by the word AND and addition by the word OR. The symbols in the equations can stand for collections of objects (sets) or statements in logic. For example: if x is the set of all green cars and y is the set of all big cars, then x+y is the set of all cars that are green or big, and xy is the set of all cars that are green and big. I

The Universe of Discourse

Relational Algebra Universe of discourse: When I started getting into database logic, I often came across the expression “universe of discourse”. When I tried to understand what exactly it is really, most answers I found referred to it as “a set”. Well it didn’t help much to me understanding one concept by naming it another. So after studying the subject thoroughly, here’s what i found : The universe of discourse is at its core really is a set (wait...what?...but..), but before we dive right into it let's take a step back for a second: the term “universe of discourse generally refers to a collection of objects being discussed in a specific discourse. The concept universe of discourse is generally attributed to De morgan (1846) but the name was used for the first time by George boole (1854). ( boole's definition ). So now after we know that a universe is a “collection” so to speak, let’s take it up a notch. To understand best what the universe

Personality prfofile #2 | Georg Cantor

Cantor and his theory of sets “The essence of mathematics lies in its freedom” Georg Cantor (1845-1918). The development of cantor’s set theory: Georg cantor was a german mathematician who in the late 19th century, funded the theory of sets. To best understand Cantor's theory, I would like to give a little background to nineteenth century mathematics. Until the end of the nineteenth century no mathematician had managed to describe the infinite, beyond the idea that it is an absolutely unattainable value. However,towards the late 19th century, the German mathematician, Weierstrass, gave a mathematically and logical solid definition of a limit and it is his definition of a limit that we use today and on which the calculus is founded. But, as often happens, the resolution of one problem drew attention to another problem. It turned out that defining a limit ne