Laravel is a powerful and popular PHP web application framework known for its elegant syntax and robust features. It simplifies the development of web applications by offering a wide range of tools, including routing, authentication, database management, and more.

Authentication in Laravel is one of the fundamental aspects of web development, ensuring that users are who they claim to be before granting access to certain parts of a website or application. 

Login with Google in Laravel is a seamless way to enhance user authentication in your web applications. It allows users to add authentication via Google, eliminating the need to remember additional login details.

This feature is not only convenient for users but also simplifies the development process for Laravel developers. In this tutorial, I'll take you through the steps of effortlessly login with Google in Laravel application using its external library, Laravel Socialite. Socialite currently supports authentication along many platforms like Google,  Facebook, Twitter, LinkedIn, GitHub, GitLab, and Bitbucket. 

You see, Google sign in is widely used on social websites. It simplifies the login process, bypassing the need for email validation. Have you ever skipped email validation?

Using social logins like Google enhances user experience and saves time on verification code implementation.

To enjoy these benefits, you must set up Google authentication in Laravel. Don't worry if you're unsure how – I've got you covered!

In this article, I'll walk you through the steps to enable Google login using the Laravel Socialite package. Following these steps, you can quickly sign in, sign up with your Google account, and use Google authentication for Laravel 8 login.

Steps for Google Authentication Login in Laravel 8 Using Socialite Package

Let's begin!

Step 1: Install a Laravel Project

First, make sure your computer has a Laravel project. If it doesn't, you can install it using the below command.

Run this command in Command Prompt:

“composer create-project –prefer-dist laravel/laravel googleLogin”

This command will help you to download it into your system successfully. 

Step 2: Install the Socialite Package

After you've got your Laravel project downloaded, it's time to install Socialite package. Wondering how to do that?

To download the socialite package, simply run this command:

“composer require laravel/socialite”

Once you've downloaded 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's a screenshot of the folder directories for reference:

Next, you'll find a file named “app” right inside the config folder.

Once you've opened this file, go ahead and paste these lines:

“'providers' => [

    LaravelSocialiteSocialiteServiceProvider::class,

],

‘aliases' => [

    ‘Socialite' => LaravelSocialiteFacadesSocialite::class,

],”

Some text will appear on your screen.

Step 3: Create a Google client ID and secret ID

Laravel makes it easy to authenticate with OAuth providers using Laravel Socialite. Hereby, let's make a Google client ID and secret ID. If you don't already have a Google app account, you can create one right here at the Google Developers Console

You'll see a screen that looks like the screenshot below:

Simply click on “credentials” and select “OAuth client ID“.

After you've successfully created the authentication ID, you'll receive both the client ID and client secret ID.

In this step, you need to specify your redirect URL, just like it's shown in the screenshot below:

Step 4: Create a Migration for Adding Google ID

In this step, you have to create a migration for adding google_id in your user table. To do this, use the following command:

“php artisan make:migration add_google_id_column”

Here you can find the migration file in the database folder for reference.

Now, open the migration file and paste the code provided below to continue:

“$table->string(‘google_id')->nullable();”

The screenshot below will provide a clearer understanding of how to carry out this process:

Next, execute the command: “php artisan migrate“.

After running this command your column (Google id) will be added to your database automatically, just as seen in the screenshot below:

Step 5: Define a Route for Socialite Login with Google

Once the google_id column is added, you have to incorporate a new route for Google login. For this, add the below route in web.php file. Follow the screenshot to find the route file in your project. 

Simply open the file and copy-paste the code provided below:

“Route:get(‘google’,function(){

Return view(‘googleAuth’);

})

Route::get(‘auth/google', ‘AuthLoginController@redirectToGoogle');

Route::get(‘auth/google/callback', ‘AuthLoginController@handleGoogleCallback');”

Step 6: Handling Google Callback

Now, you need to add a method of Google authentication that will surely help you in handling Google callback.

For this, paste the code provided below in your LoginController.php file:

“app/Http/Controllers/Auth/LoginController.php”

You can check out the screenshot below to know where the controller is located. 

If you want to make a new controller, you can use this command to finish this step:

“Php artisan make:controller GoogleLogin”

Now, open the respective controller file and paste the code as added below- 

<?php

namespace AppHttpControllersAuth;

use AppHttpControllersController;

use IlluminateFoundationAuthAuthenticatesUsers;

use Socialite;

use Auth;

use Exception;

use AppUser;

class LoginController extends Controller

{

    use AuthenticatesUsers;

    public function __construct()

    {

        $this->middleware(‘guest')->except(‘logout');

    }

    public function redirectToGoogle()

    {

        return Socialite::driver(‘google')->redirect();

    }

    public function handleGoogleCallback()

    {

        try {

            $user = Socialite::driver(‘google')->user();

            $finduser = User::where(‘google_id', $user->id)->first();

            if($finduser){

                Auth::login($finduser);

                return return redirect(‘/home');

            }else{

                $newUser = User::create([

                    ‘name' => $user->name,

                    'email' => $user->email,

              ‘google_id'=> $user->id

                ]);

                Auth::login($newUser);

                return redirect()->back();

            }

        } catch (Exception $e) {

            return redirect(‘auth/google');

        }

    }

}

Step 7: Add a Blade View

In this final step, you need to add a blade view. For this, you need to create a new file googleAuth.blade.php file by adding below added code:

resources/views/googleAuth.blade.php

You will get a view file in resource/view:

In the view folder, you can create your view file- 

After creating the view file, paste this code:

<!DOCTYPE html>

<html>

<head>

    <title>Laravel 5.8 Login with Google Account Example</title>

</head>

<body>

    <div class=”container”>

       <div class=”row”>

       <div class=”col-md-12 row-block”>

<a href=”{{url(‘auth/google’)}} “class=”btn bth-lg-primaty btn-block ”>

          <strong>Login With Google</strong>

          </a> 

         </div>

       </div>

    </div>

</body>

</html>

I personally applied the google auth login in GPE( Guest Post Engine). For better understanding, I am sharing a screenshot.

Here you will see Google sign-in button- 

Now, if I'll click the button, it will redirect to the google sign page, as shown below.

Here you go! 

Points to Consider

Remember to consider the following points when you follow above mentioned steps for Socialite login with Google account:

  • You might encounter issues with redirecting your page to Google. If you come across an error like the one below, you only need to modify two lines of code in your controller.

Here is the code that you need to update:

“return Socialite::driver(‘google')->stateless()->redirect();”

  • I suggest double-checking your redirect URL in the Google Developer Console. This will ensure a smooth task completion without any obstacles.

Ready to Login with Google in Laravel?

Congratulations folks! You have successfully logged in with Google in Laravel. Now. you don't have to worry about remembering your passwords for different profiles. 

This step-by-step tutorial has equipped you with the knowledge to integrate Google login into your Laravel application. This enhances user convenience and simplifies the authentication process for you as a developer. Now, you've empowered your Laravel project with the ability to offer a more user-friendly and efficient login experience.

I hope the above-added steps and images are clear and will surely help you hit your target.

If you still need any help in website development and creating a professional website, feel free to contact us.

Frequently Asked Questions

Laravel provides a solid foundation for building secure login systems, but the security of a Laravel login system ultimately depends on how well it's implemented and configured. Laravel automatically hashes user passwords using the bcrypt algorithm, which is a strong and secure way to store passwords. This ensures that plaintext passwords are never stored in the database.

Laravel provides a solid foundation for building secure login systems, but the security of a Laravel login system ultimately depends on how well it's implemented and configured. Laravel automatically hashes user passwords using the bcrypt algorithm, a strong and secure way to store passwords. This ensures that plaintext passwords are never stored in the database.

Social login, also known as social authentication or social sign-in, is a feature that allows users to log in to a web application or website using their existing social media credentials from platforms like Facebook, Google, Twitter, or LinkedIn, rather than creating a new account with a separate username and password. Laravel provides a straightforward way to implement social login in your web applications through various packages and libraries.

In Laravel, an ORM (Object-Relational Mapping) is a database abstraction layer that allows developers to interact with a database using object-oriented syntax and methods instead of writing raw SQL queries. Laravel's ORM is called Eloquent, and it simplifies database operations by mapping database tables to PHP objects, making it easier to work with databases in your web applications.