In the past, I have written an article Login with LinkedIn Using Laravel Socialite. One of our readers asked about integrating Google Login in Laravel. Google sign-in is one of the popular platforms used for social login on the website.
When you allow users to login with their social profile, you skip the process of validating their email. Your users don’t need to follow an email activation process. We can rely on social sites as they already validated users on their platforms. It gives a better user experience as users don’t need to create and remember their login credentials for your website. It also saves you time in building a verification flow.
In this article, we study step by step guide on adding Google Login in Laravel using Laravel Socialite. Laravel Socialite package handles OAuth flow for social login. This package speeds up the process of integrating social login on Laravel.
Install Laravel and Database Configuration
For this tutorial, I’ll use a fresh Laravel installation. Run the below command to install Laravel for you:
composer create-project laravel/laravel googlelogin
Upon Laravel installation, create a database and add your database credentials to the .env
file. To integrate social login into the application, I will add 2 more columns – provider
and provider_id
to the user migration file. The provider
column holds the name of the social site say ‘google’. And the provider_id
will store the social profile id of a user.
Open your user’s migration file and add the code below to the up
method.
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->string('provider');
$table->string('provider_id');
$table->rememberToken();
$table->timestamps();
}
}
Next, create the users
table by running the migrate command.
php artisan migrate
You also need to add new columns to the User model.
app/Models/User.php
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'provider', 'provider_id',
];
Create Google Application and Get Your Credentials
For Google login integration, you need to register a project on the Google APIs console. We will require the client id and client secret of the application to complete the OAuth flow of the users.
Follow the steps below to create a Google application and get the credentials. For the sake of the tutorial, I am using the local server URL. You can adjust this URL as per your requirement.
- Go to the Google Developer Console.
- Click on the drop-down and create a new project by clicking on the (+) sign. Alternatively, you can also select the existing project.
- On the project dashboard select Credentials from the sidebar.
- Under the Credentials tab, click on the Create credentials drop-down and select OAuth client ID.
- Select the Web application from the Application type. In the Authorized redirect URLs enter the URL
http://localhost:8000/google/callback
.
After completing the above steps, you will get the popup along with your Client ID and Client Secret. Copy these keys, they will require in the later part of the tutorial.
Create Routes and Controller
You are ready with the API keys. Now to proceed further we have to create routes, a view, and a controller. First, let’s create a LoginController
using the command:
php artisan make:controller LoginController
After this, create a login.blade
file and add the below HTML to it.
<a href="{{ url('/login/google') }}">
{{ __('Login with Google') }}
</a>
Call this view from the index
method of LoginController
.
public function index()
{
return view('login');
}
To complete the login flow, you need to add a few routes. Add the below routes to the routes/web.php
file.
Route::get('login', 'LoginController@index');
Route::get('login/{provider}', 'LoginController@redirectToProvider');
Route::get('{provider}/callback', 'LoginController@handleProviderCallback');
Route::get('/home', function () {
return 'User is logged in';
});
Here, I added a home
route. When a user login with Google, I will redirect them to the home
route. It’s for demo purposes. You should change this route to something else.
Google Login in Laravel Using Laravel Socialite
We are done with the basic setup required for social login. Now, install the Laravel Socialite library by running the below command in the terminal.
composer require laravel/socialite
Upon installation of the library, open the config/services.php
and add Google configuration as follows:
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URL'),
],
Here we used env()
method to get credentials that mean you should add these credentials to the .env
file.
GOOGLE_CLIENT_ID=YOUR_CLIENT_ID
GOOGLE_CLIENT_SECRET=YOUR_CLIENT_SECRET
GOOGLE_REDIRECT_URL=http://localhost:8000/google/callback
Make sure to replace the placeholders with actual values. Finally, we need to add code in LoginController.php
file that redirects the user to the Google login page and in return handles the response. In this file, I am writing a function that redirects a user to the Google login page, and on successful authorization, it will insert user details in the database and log the user in.
LoginController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Socialite;
use App\Models\User;
use Auth;
class LoginController extends Controller
{
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Call the view
*/
public function index()
{
return view('login');
}
/**
* Redirect the user to the Google authentication page.
*
* @return Response
*/
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
/**
* Obtain the user information from Google.
*
* @return Response
*/
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect($this->redirectTo);
}
/**
* If a user has registered before using social auth, return the user
* else, create a new user object.
* @param $user Socialite user object
* @param $provider Social auth provider
* @return User
*/
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
return User::create([
'name' => $user->name,
'email' => $user->email,
'provider' => $provider,
'provider_id' => $user->id
]);
}
}
In the controller file, we are checking if the user with provider_id
already exists. If it exists return the current user instance else insert details in the users
table.
That’s it! This is how one can integrate Google Login in Laravel using the Socialite package. Please go ahead and give it a try. I hope it will save you time and effort. I would like to hear your thoughts and suggestions in the comment section below.
Related Articles
- Login with Google using JavaScript and PHP
- Login with Twitter in Laravel Using Laravel Socialite
- How to Add Google OAuth Login in Website with PHP
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
great <3
Stuck on same issue 🙁
Socialite: InvalidStateException in AbstractProvider.php
Laravel \ Socialite \ Two \ InvalidStateException
C:\wamp64\www\laravel-dev\vendor\laravel\socialite\src\Two\AbstractProvider.php