By using the socialite package, you can create functionality for login with google in Laravel 8. In our previous tutorial, I already created the Facebook login in Laravel 8 using socialite. Similarly, you can create the Google login functionality. The Google login authenticates the user using OAuth. After the successful login, it will return the user detail. You can store it inside the database table. So, that it will identify the current logged user. We will start from very basic so if you are a beginner in Laravel then no need to worry. You will be able to understand and implement login with google very easily. We will create a new application in Laravel 8.
Prerequisites
For creating this project, you will require to have the following configurations-
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create a New Project For Login with Google
For creating a new project, just open the terminal and hit the below command.
composer create-project --prefer-dist laravel/laravel laravel-socialite
The above command will start installing Laravel 8 in the project folder.
After creating the project, let’s open it into the editor. Here, I am using VS Code editor.
How to Schedule Tasks with Cron Job in Laravel 8
Create and Configure Database
Firstly, you will require to have a database. So, just create it. For the database, I am using here MySQL.
CREATE DATABASE laravel_socialite;
After creating the database, come to the Laravel project and configure the database credentials.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_socialite
DB_USERNAME=root
DB_PASSWORD=root
Now, we have configured the database. Hence, in the next step, we will install the UI auth package for login with google.
Install UI Auth Package For User Authentication
For implementing the Google Login functionality in Laravel, firstly, we will require user authentication options. So, why don’t we go with the inbuilt auth package? Yes, we will install the Laravel UI auth package. It will provide the Login, Register, Logout options.
composer require laravel/ui
This package will update the composer.json file after adding the UI authentication.
This package will require installing the auth scaffolding for the User authentication system.
Import and Export CSV and Excel File in Laravel 8
Install Auth Scaffolding in Laravel 8
Here, you can opt for bootstrap auth or vue auth. Both will be working as same. I will opt vue auth. So, hit the below command in the terminal.
php artisan ui vue --auth
After adding the vue auth package, you will require to install npm. The npm will provide the front-end dependencies for UI auth.
npm install && npm run dev
After installing npm the CSS and js file will build for the use.
After that, you can test the application. As a result, we have the Login and Register option provided by the Laravel UI.
When you will click on the Login option, it will open the below result.
In the next step, we have to add the socialite package.
How to Generate PDF File in Laravel 8 Using DOM PDF
Install Socialite Package For Login with Google
Please make sure, you are inside the project directory. Now, hit the below command for installing the socialite package in Laravel.
composer require laravel/socialite
After installing the socialite package, we will move to the next step.
RESTful APIs For Todo App Using Passport Auth in Laravel 8
Add Provider and Alias for Socialite
After installing the socialite package, it is required to register in the config/app.php. Add the provider and create one alias for it.
'providers' => [
...
...
...
Laravel\Socialite\SocialiteServiceProvider::class,
],
'aliases' => [
...
...
...
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],
Create Google App
Before implementing Login with Google functionality, you will require a Google app first. This app will help to get the OAuth Client ID for creating the user authentication. You can create the new app by visiting the Google Developer Console.
You will have the dashboard of the Google Cloud platform.
- Firstly, create a new app if don’t have one.
- After creating the app, go to the Credentials and then click on the Create Credentials.
- Now, click on OAuth client Id. Here, we have to create the OAuth client Id for the selected app.
- While creating the OAuth Client Id, it will ask you to register the app name.
- So, if you are developing it locally then simply put the localhost in the URIs section.
- Next, you have to set the authorized redirect URIs. So, simply put the callback URL in which we want to get the response.
- Hence, here, I have set the URL and we will create this route in our Laravel application.
- After configuration, you will have the OAuth Client Id and the Client Secret. So, just copy it and return back to the Laravel application.
How to Implement Invisible reCAPTCHA in Laravel 8
Configure Google OAuth Client in Laravel Application
Go to the Laravel project folder. Now, open the services.php file under the config folder. Inside the return array, simply put the below array for the Login with Google.
return [
...
...
...
'google' => [
'client_id' => 'GOOGLE_APP_CLIENT_ID',
'client_secret' => 'GOOGLE_APP_CLIENT_SECRET',
'redirect' => 'http://localhost:8000/auth/google-callback',
],
];
Also, put the client id and the client secret there. Lastly, we have to set the same callback URL that we registered in the Google App. That’s it for the configuration.
Create Authentication in Laravel 8 Using Laravel Breeze
Add Field in User Migration
We will require to add a column in the existing users table migration. So, that we can store the Google Logged user id. We can achieve in two ways. We can create a separate migration file for the users table. Or we can add it to the existing users migration file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->string('google_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Here, I have added a field in the users migration file. Now, run the migration command to migrate the tables.
php artisan migrate
After the migration, we have the users table schema in the database.
User Authentication in Laravel 8 Using UI Auth Package
Set Fillable Data in User Model
After the migration, we have to set the fillable data in the User model. When you will open the User.php file, you will see the default fillable data array. So, in this array, we have to add one more filed that we have added in the migration.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, 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',
];
}
In the next step, we will create a controller for implementing the Login with Google.
Create a Controller in Laravel 8
For implementing the Login with Google functionality in Laravel, we will have to create a controller. Hence, open the terminal and create a controller by hitting the below command.
php artisan make:controller SocialiteAuthController
After creating the controller, simply add the below snippet there.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Socialite;
use Illuminate\Support\Facades\Auth;
use Exception;
class SocialiteAuthController extends Controller
{
public function googleRedirect()
{
return Socialite::driver('google')->redirect();
}
/**
* Google login authentication
*
* @return void
*/
public function loginWithGoogle()
{
try {
$googleUser = Socialite::driver('google')->user();
$user = User::where('google_id', $googleUser->id)->first();
if($user){
Auth::login($user);
return redirect('/home');
}
else{
$createUser = User::create([
'name' => $googleUser->name,
'email' => $googleUser->email,
'google_id' => $googleUser->id,
'password' => encrypt('test@123')
]);
Auth::login($createUser);
return redirect('/home');
}
} catch (Exception $exception) {
dd($exception->getMessage());
}
}
}
In the next step, add the routes for managing the Google OAuth Login.
Remove Uploaded Image in Laravel 8 From Public Folder
Create Routes for Login with Google
As we have already registered a callback URL in the Google app. Hence, we will have to define the endpoints in the web.php file. So, open the web.php file and put the routes there.
Route::get('google', [SocialiteAuthController::class, 'googleRedirect'])->name('auth/google');
Route::get('/auth/google-callback', [SocialiteAuthController::class, 'loginWithGoogle']);
At last, we have to create a button for Google Login. Through this button, you will be redirected to the Google account for OAuth login.
Create a Login with Google Button in View
For creating the button, we will go to the login.blade.php. In the login blade file, we already have the Login button and other functionalities. We have to create another button there.
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
@csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-secondary">
{{ __('Login') }}
</button>
<!-- Google Login Button -->
<a href="{{ route('auth/google') }}" class="btn btn-danger">
{{ __('Login with Google') }}
</a>
</div>
<div class="col-md-8 offset-md-4">
@if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
@endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
Now, we are done with the Google login functionality. Save and run the application to see the result.
How to Configure PHPMailer in Laravel 8 For Sending Email
Check Result of Login with Google in Laravel
When you will click on the Login option, you will have the below page. Here, you can see, we have the Google login button. After clicking on the Login with Google button, you will be redirected to the Google OAuth login page.
Here, when I clicked on the Login with Google button, it redirected me to the Google login page. In the google login page, you can notice one thing, here the sign in permission is for the created Google App.
After giving the Email and correct password, you will be redirected back to the callback URL. In the callback URL, we have set the dashboard page.
Conclusion
We have created a Login with Google functionality in Laravel 8. Firstly, we have created the Laravel application, and then after the database configuration, we used the Laravel UI Auth. The Laravel UI Auth is just for managing the login, logout, and session functionality. For Google Login, we just need the socialite package, and the OAuth Client id, and the client secret. You can get the client id and client secret by creating an app in the google developer console. So, I hope every step is simple and easy to follow. But, in case if you get any issues then please don’t forget to write your query in the comment section. Thank you.
Wanuja says
Really Useful, Thanks for sharing