A Comprehensive Tutorial on Implementing Google Login in a Laravel Application
Steps for Google Authentication Login in Laravel
Let's begin..
Step-1 Firstly, you need to check whether your system has a laravel project or not. If not, then you can download it by using the below-mentioned command.
Run this command in Command Prompt:
composer create-project --prefer-dist laravel/laravel withgoogleLogin
This command will help you to successfully download in your system.
Step-2 Once you download a laravel project, it's time to install the socialite package. Are you thinking how?
To download the socialite package you can run this command-
composer require laravel/socialite
After downloading the socialite package, you need to add providers and aliases in the config file. Now open config/app.php file and incorporate the service provider and alias. Here is the screenshot of folder directories :
add these line in config/app.php
'providers' => [
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
Step-3 Now, it's time to create a google client id and secret id. Say if you don't have a google app account, it's time to create one from here- Google Developers Console.
add http://127.0.0.1:8000/ url in callback input
Step-4
add routes in web.php
Route::get('/auth/google', [HomeController::class, 'redirectToGoogle']);
Route::get('/auth/google/callback', [HomeController::class, 'handleGoogleCallback']);
Step-5
add function to HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Laravel\Socialite\Facades\Socialite;
use Auth;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
// $this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
public function handleGoogleCallback()
{
$user = Socialite::driver('google')->user();
// $user contains user details obtained from Google
// auth()->login($user);
dd($user);
// You can now create or authenticate the user in your application
}
}
now run laravel server
php artisan serve
and open this url
http://127.0.0.1:8000/auth/google