Share this:

Welcome to this tutorial on integrating Google login into a Laravel 9 project. Laravel is a popular PHP framework that simplifies web development and makes it easy to build robust, feature-rich applications. In this tutorial, we will show you how to add a Google login button to your Laravel app and handle the login process using the Laravel Socialite package.

Social media login options are becoming increasingly important for modern web applications, as they allow users to easily register and log in using their existing social media accounts. This can improve the user experience and make it more convenient for users to access your app. By integrating Google login into your Laravel project, you can provide an additional login option for your users and make it easier for them to get started with your app.

In this tutorial, we will walk you through the steps of setting up Google API credentials, installing the Laravel Socialite package, and adding the Google login button to your login form. We will also cover how to handle the login process and protect routes that should only be accessible to logged-in users. By the end of this tutorial, you will have a fully functional Google login integration in your Laravel 9 app.

Integrating Google login into a Laravel 9 Project
Integrating Google login into a Laravel 9 Project

Setting up Google API credentials

To get started with integrating Google login into your Laravel 9 project, you will first need to set up Google API credentials. Here’s how to do it:

  1. Go to the Google Cloud Console (https://console.cloud.google.com).
  2. Click the project drop-down and select or create the project that you want to use for the API.
  3. Click the hamburger menu and select APIs & Services > Credentials.
  4. On the Credentials page, click Create credentials > OAuth client ID.
  5. Select Web application as the application type.
  6. In the Authorized JavaScript origins field, enter the URL of your Laravel app.
  7. In the Authorized redirect URIs field, enter the URL of your Laravel app, followed by “/login/google/callback”.
  8. Click the Create button.

Google will then generate a client ID and secret for your app. You will need to use these credentials to configure the Laravel Socialite package, which we will cover in the next section.

Installing Laravel Socialite package

To integrate Google login into your Laravel 9 app, you will need to install the Laravel Socialite package. Here’s how to do it:

  1. Open a terminal window and navigate to your Laravel project directory.
  2. Run the following command to install Socialite:
composer require laravel/socialite
  1. In your Laravel app, open the config/services.php file. This file contains the credentials for various third-party services that your app may use.
  2. Add the following code to the services array to configure Socialite with your Google API credentials:
'google' => [
    'client_id' => 'YOUR_GOOGLE_CLIENT_ID',
    'client_secret' => 'YOUR_GOOGLE_CLIENT_SECRET',
    'redirect' => 'YOUR_LARAVEL_APP_URL/login/google/callback',
],
  1. Replace YOUR_GOOGLE_CLIENT_ID and YOUR_GOOGLE_CLIENT_SECRET with the client ID and secret that you obtained from the Google Cloud Console. Replace YOUR_LARAVEL_APP_URL with the URL of your Laravel app.
  2. Save the services.php file and close it.

That’s it! You have now installed and configured the Laravel Socialite package for use with your Google login integration. In the next section, we’ll show you how to add a Google login button to your login form.

Adding Google login button to login form

To add a Google login button to your Laravel app’s login form, you will need to add a link that triggers the Google login process when clicked. Here’s how to do it:

  1. Open the resources/views/auth/login.blade.php file in your Laravel project. This is the view file for the login form.
  2. Scroll down to the bottom of the file and add the following code just before the closing </form> tag:
<a href="{{ url('login/google') }}" class="btn btn-secondary btn-block">
    <i class="fab fa-google"></i> Login with Google
</a>

This code creates a link that, when clicked, sends the user to the login/google route, which we will define in the next section. The btn and btn-secondary classes are bootstrap classes that will style the link as a button. You can customize the button’s appearance by adding your own CSS styles or using different bootstrap classes.

That’s it! You have now added a Google login button to your login form. In the next section, we’ll show you how to handle the login process when the button is clicked.

Handling the login process

To handle the login process when the Google login button is clicked, you will need to create a route and a controller method to handle the login request. Here’s how to do it:

  1. In your Laravel app, open the routes/web.php file.
  2. Add the following route to the file:
Route::get('login/google', 'Auth\LoginController@redirectToGoogle');

This route will trigger the Google login process when the user clicks the Google login button.

  1. Open the app/Http/Controllers/Auth/LoginController.php file and add the following method to the class:
public function redirectToGoogle()
{
    return Socialite::driver('google')->redirect();
}

This method uses the Laravel Socialite package to redirect the user to the Google login page.

  1. Add the following route to the routes/web.php file:
Route::get('login/google/callback', 'Auth\LoginController@handleGoogleCallback');

This route will handle the callback from Google after the user has logged in.

  1. Add the following method to the LoginController class:
public function handleGoogleCallback()
{
    try {
        $user = Socialite::driver('google')->user();
    } catch (\Exception $e) {
        return redirect('login');
    }

    // check if they're an existing user
    $existingUser = User::where('email', $user->email)->first();
    if($existingUser){
        // log them in
        auth()->login($existingUser, true);
    } else {
        // create a new user
        $newUser                  = new User;
        $newUser->name            = $user->name;
        $newUser->email           = $user->email;
        $newUser->google_id       = $user->id;
        $newUser->avatar          = $user->avatar;
        $newUser->avatar_original = $user->avatar_original;
        $newUser->save();
        auth()->login($newUser, true);
    }
    return redirect()->to('/home');
}

This method uses the Laravel Socialite package to retrieve the user’s Google account information and logs the user in. If the user is not an existing user in your app’s database, it creates a new user account. You can customize this method to fit your app’s needs.

That’s it! You have now set up the necessary routes and controller methods to handle the Google login process in your Laravel 9 app. In the next section, we’ll show you how to protect routes that should only be accessible to logged-in users.

Also Read: Step-by-Step Guide on How to Implement Laravel Login with Mobile Number OTP

Protecting routes

To protect routes that should only be accessible to logged-in users in your Laravel 9 app, you can use the built-in auth middleware. Here’s how to do it:

  1. In your Laravel app, open the routes/web.php file.
  2. Add the auth middleware to any route that should only be accessible to logged-in users. For example:
Route::middleware('auth')->group(function () {
    Route::get('/home', 'HomeController@index');
});

This will prevent unauthenticated users from accessing the /home route.

You can also apply the auth middleware to a specific route by attaching it to the route’s definition. For example:

Route::get('/profile', 'ProfileController@index')->middleware('auth');

This will prevent unauthenticated users from accessing the /profile route.

You can also create your own custom middleware to handle route protection. For more information, you can refer to the Laravel documentation on middleware (https://laravel.com/docs/middleware).

That’s it! You have now learned how to protect routes in your Laravel 9 app using the built-in auth middleware. In the next section, we’ll show you how to test your Google login integration to make sure it’s working properly.

Testing the integration

To test your Google login integration in your Laravel 9 app, you can follow these steps:

  1. Start your Laravel development server by running the following command in your terminal:
php artisan serve
  1. Open a web browser and go to the URL of your Laravel app.
  2. Click the Google login button on the login form.
  3. If you are not already logged in to your Google account, you will be prompted to log in. After logging in, you will be redirected back to your Laravel app.
  4. If the integration is working properly, you should now be logged in to your app. You can verify this by checking for the presence of a “logout” button or by trying to access a route that is protected by the auth middleware.
  5. To log out, click the logout button or visit the logout route (usually /logout).

That’s it! You have now tested your Google login integration in your Laravel 9 app. If you encounter any issues or errors during the testing process, you can refer to the Laravel logs (located in the storage/logs directory) for more information.

Conclusion

In conclusion, integrating Google login into a Laravel 9 app is a straightforward process that can provide a convenient and user-friendly login option for your users. By following the steps outlined in this tutorial, you can set up Google API credentials, install the Laravel Socialite package, add a Google login button to your login form, handle the login process, and protect routes that should only be accessible to logged-in users.

By adding social media login options to your app, you can improve the user experience and make it easier for users to register and log in. Google login is a popular and widely used option, and integrating it into your Laravel app can help you attract and retain more users.

I hope this tutorial has been helpful to you, and I wish you the best of luck with your app development. If you have any questions or need further assistance, don’t hesitate to ask. Happy coding!

Also Read: How to Retrieve an Array of Ids from Eloquent Models in Laravel

Share this:

Categorized in: