Simple Google Login Laravel 8 Socialite
Today learn this example of laravel 8 login with google plus PHP. This article will give you a simple example of laravel 8 google plus sign in with Gmail account. you will learn laravel 8 jetstream login with google in this article.
This tutorial will give you a simple example of login with Gmail in laravel 8 in your project.
As we know social media becomes more and more popular in the world laravel social login. everyone user has a social account like Gmail, Facebook, etc. I think also must have a Gmail account. So if in your application have login with social then it becomes awesome. you got more people to connect with your website because most people do not want to fill sign up or sign in form. If there login with social than it becomes awesome.
So if you want to also implement login with google Gmail account then I will help you step by step instruction.
If you haven't laravel 8 application setup then we have to get a fresh laravel 8 application. So run bellow command and get a clean fresh laravel 8 application.
composer create-project --prefer-dist laravel/laravel googleLogin
In this step, we need to use the composer command to install jetstream, so let's run bellow command and install the bellow library.
composer require laravel/jetstream
we need to create authentication using the bellow command. you can create basic login, register, and email verification. if you want to create team management then you have to pass an additional parameter. you can see bellow commands:
php artisan jetstream:install livewire
Now, let's node js package:
npm install
let's run package:
npm run dev
now, we need to run the migration command to create a database table:
php artisan migrate
We will install the Socialite Package that provides API to connect with google account. So, first, open your terminal and run bellow command:
composer require laravel/socialite
we need google client id and secret that way we can get information from other users. so if you don't have a google app account then you can create from here: Google Developers Console. you can find bellow screen :
Now you have to click on Credentials and choose the first option oAuth and click the Create new Client ID button. now you can see the following slide:
after create an account you can copy the client id and secret.
Now you have to set app id, secret and call back URL in the 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://localhost:8000/auth/google/callback', ], ]
This step first we have to create a 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/Models/User.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Fortify\TwoFactorAuthenticatable; use Laravel\Jetstream\HasProfilePhoto; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens; use HasFactory; use HasProfilePhoto; use Notifiable; use TwoFactorAuthenticatable; /** * 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', 'two_factor_recovery_codes', 'two_factor_secret', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; /** * The accessors to append to the model's array form. * * @var array */ protected $appends = [ 'profile_photo_url', ]; }
After adding the google_id column first we have to add a new route for google login. so let's add bellow route in the routes.php file.
app/Http/routes.php
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\GoogleController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('auth/google', [GoogleController::class, 'redirectToGoogle']); Route::get('auth/google/callback', [GoogleController::class, 'handleGoogleCallback']);
We need to add a method of google auth that method will handle google callback URL and etc, first put bellow code on your GoogleController.php file.
app/Http/Controllers/GoogleController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Laravel\Socialite\Facades\Socialite; use Exception; use App\Models\User; use Illuminate\Support\Facades\Auth; class GoogleController extends Controller { /** * Create a new controller instance. * * @return void */ public function redirectToGoogle() { return Socialite::driver('google')->redirect(); } /** * Create a new controller instance. * * @return void */ public function handleGoogleCallback() { try { $user = Socialite::driver('google')->user(); $finduser = User::where('google_id', $user->id)->first(); if($finduser){ Auth::login($finduser); return redirect()->intended('dashboard'); }else{ $newUser = User::create([ 'name' => $user->name, 'email' => $user->email, 'google_id'=> $user->id, 'password' => encrypt('123456dummy') ]); Auth::login($newUser); return redirect()->intended('dashboard'); } } catch (Exception $e) { dd($e->getMessage()); } } }
Ok, now at last we need to add a blade view so first create a new file login.blade.php file and put the bellow code:
resources/views/auth/login.blade.php
<x-guest-layout> <x-jet-authentication-card> <x-slot name="logo"> <x-jet-authentication-card-logo /> </x-slot> <x-jet-validation-errors class="mb-4" /> @if (session('status')) <div class="mb-4 font-medium text-sm text-green-600"> {{ session('status') }} </div> @endif <form method="POST" action="{{ route('login') }}"> @csrf <div> <x-jet-label value="Email" /> <x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus /> </div> <div class="mt-4"> <x-jet-label value="Password" /> <x-jet-input class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" /> </div> <div class="block mt-4"> <label class="flex items-center"> <input type="checkbox" class="form-checkbox" name="remember"> <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span> </label> </div> <div class="flex items-center justify-end mt-4"> @if (Route::has('password.request')) <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}"> {{ __('Forgot your password?') }} </a> @endif <x-jet-button class="ml-4"> {{ __('Login') }} </x-jet-button> </div> <div class="flex items-center justify-end mt-4"> <a href="{{ url('auth/google') }}"> <img src="https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png" style="margin-left: 3em;"> </a> </div> </form> </x-jet-authentication-card> </x-guest-layout>
I hope it can help you...
Leave a Reply