Cookie

This site uses tracking cookies used for marketing and statistics. Privacy Policy

Laravel Socialite: A complete Guide for 2025

January 28th, 2025
Laravel Socialite: A complete Guide for 2025.

Introduction

Social logins are becoming an important part of most applications. Users prefer to sign up to applications by using social credentials as it saves them time and is also convenient for them. A Laravel socialite package enables developers to add social logins to their application with all ease.

In this article, we are going to show you how to add social implementation to your application.

Let’s first begin by understanding what is Laravel Socialite.

What is Laravel Socialite

What is Laravel Socialite.

Laravel socialite is a complete package which is developed in order to ease the implementation of social authentication by removing all the complexities that are involved. With this package, a developer is able to add the social authentication aspect to their application with convenience, thus enabling them to be productive enough in the whole process.

Socialite currently supports authentication Facebook, Twitter, GitHub, Google, etc., social platforms. Moreover, the developers have also built other community driven providers as well. The community named as Socialite providers have factored in most of the other Laravel Socialite Oauth providers which can be useful to have on your application. Lastly, Apple and Instagram are some more platforms available through other Laravel socialite providers.

Now, further let us talk about the benefits of Laravel Socialite.

Master Social Authentication with Laravel

Learn and implement Laravel Socialite with ease. Or let our experts handle it for you! We provide tailored solutions for seamless Google, Facebook, and Twitter login integration.

What are the benefits of Laravel Socialite?

What are the benefits of Laravel Socialite?.

Integrating social logins by using Laravel Socialite provides a number of advantages

  • User convenience: Users can easily sign up or log in using existing social media accounts, reducing the room for friction during the registration process.

  • Enhanced security: Social logins often offer a better security measure as compared to traditional email/password combination.

  • Reduced development time: Developers can save an abundance of time by using a pre-built solution for social authentication instead of implementing it from the start.

  • Access to user data: Social logins enables applications to access user profile information easily, which can enhance the user experience.

Now, further let us talk about how to use Laravel Socialite.

How to use Laravel Socialite?

How to use Laravel Socialite?.

Installation

To keep you going, Laravel Socialite authentication, use Composer package manager to add the dependency to your application.

composer require laravel/socialite

Laravel Socialite with Google

After you have installed the Socialite package, you can use it to add Google authentication to your application. In this part, we will add Google authentication to the Laravel application.

To begin, we will firstly build a google client id and a secret id. To do this, we need access to the Google Developers Console. Moreover, we’ll need to create the project and the credential related to the project.

Laravel Socialite with Google.

Now nextly, click on the credentials and opt for OAuth client id.

credentials and opt for OAuth client id.

You will receive the client and secret IDs after creating the credentials correctly.

client and secret IDs.

The redirect URL that Google will use to reroute the user after authentication must also be added.

reroute the user authentication.

Configuration

After obtaining our login credentials, we must incorporate them into our Laravel application. We'll update the config/services.php file using the credentials. The setups look like this:

'google' => [
    'client_id'     => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect'      => env('GOOGLE_REDIRECT_URL')
],

The following are the real credentials found in the.env file:

GOOGLE_CLIENT_ID=000000000000-XXXXXXXXXXX.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=XXXXXXXXXXXXX
GOOGLE_REDIRECT_URL=http://localhost:8000/callback

A simple Laravel authentication scaffold must be added after the configurations are complete. This will produce simple registration and login pages. The authentication pages can be scaffolded using Laravel Breeze, Laravel Jetstream, or Laravel/UI packages.

In this instance, I'll demonstrate using the Laravel/UI package.

I'll use the following commands to build a simple authentication user interface scaffold:

composer require laravel/ui
php artisan ui bootstrap --auth
npm install
npm run dev

Our user migration file must now be updated to accept the credentials that were acquired from Google as indicated.

.

Next, we must add our endpoints for redirection and callback, as well as setup the routes in the routes/web.php file.

Route::get('/google-redirect', [LoginController::class, 'googleRedirect']);
Route::get('/callback', [LoginController::class, 'googleCallback']);

After a user authenticates using Google as the provider, the second method will handle the response, while the first method will display the Google authentication page.

We can modify the LoginController Class with the following logic to manage the redirect:

/**
  * Redirect the user to the Google authentication page.
  *
  * @return \Illuminate\Http\Response
  */
public function googleRedirect()
{
    return Socialite::driver('google')->redirect();
}

The following code can be added to the LoginController class to manage the callback logic:

  /**
     * Obtain the user information from Google.
     *
     * @return \Illuminate\Http\Response
     */
    public function googleCallback()
    {
        try {
            $user = Socialite::driver('google')->user();
        } catch (Exception $e) {
            return redirect('/login');
        }
        // check if they're an existing user
        $existing = User::where('email', $user->email)->first();
        if ($existing) {
            // log the user in
            auth()->login($existing);
        } 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);
        }
        return redirect()->to('/dashboard');
    }

Adding a Google button to our frontend login page that points to the appropriate route—in this example, the google-redirect route—is the final step. We have set up Google authentication for our application as a result.

Now, let us further talk about Facebook Socialite authentication

Facebook Socialite Authentication

In this section, we are going to integrate Facebook authentication into the application with the use of Laravel Socialite. To log in with Facebook, we need to build a Facebook app. In order to do so, we should have a Facebook developers account to create the Facebook app later on.

Configuration

We need to add the configurations to our Laravel application. Moreover, we will add the credentials to the config/services.php file. These configurations are shown below: 

'facebook' => [
    'client_id'     => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
    'redirect'      => env('FACEBOOK_REDIRECT_URL')
    ],

We need to update our user_migration file to accommodate Facebook login credentials once a user chooses to use it.

user_migration.

We need to configure our routes in the routes/web.php files as below:

Route::get('/facebook-redirect', [LoginController::class, 'facebookRedirect']);
Route::get('/facebook-callback', [LoginController::class, 'facebookCallback']);

The first method will show the Facebook authentication page whereas the second method will be responsible towards handling the response once a user authenticates using Facebook as the provider.

To handle the redirect we can add the following logic to the LoginController Class:

/**
  * Redirect the user to the Facebook authentication page.
  *
  * @return \Illuminate\Http\Response
  */    
public function facebookRedirect()
    {
        return Socialite::driver('facebook')->redirect();
    }
The following code can be added to the LoginController class to manage the callback logic:
  /**
     * Obtain the user information from Facebook.
     *
     * @return \Illuminate\Http\Response
     */
    public function facebookCallback()
    {
        try {
            $user = Socialite::driver('facebook')->user();
        } catch (Exception $e) {
            return redirect('/login');
        }
        // check if they're an existing user
        $existing = User::where('email', $user->email)->first();
        if ($existing) {
            // log the user in
            auth()->login($existing);
        } else {
            // create a new user
            $newUser                  = new User;
            $newUser->name            = $user->name;
            $newUser->email           = $user->email;
            $newUser->facebook_id     = $user->id;
            $newUser->avatar          = $user->avatar;
            $newUser->avatar_original = $user->avatar_original;
            $newUser->save();
            auth()->login($newUser);
        }
        return redirect()->to('/dashboard');
    }

Adding a Facebook button to our login page that points to the appropriate route—in this example, the Facebook-redirect route, is the final step. Facebook authentication has been successfully added to our application.

Twitter Socialite Authentication

Socialite in Laravel allows us to log in using Twitter as well. We must use the Twitter Developer Portal to construct a Twitter application in order to accomplish this. This will provide us the app secret and Twitter client ID, which we can utilize in our Laravel application.

Supported Providers

Provider

Client ID Environment Variable

Client Secret Environment Variable

Redirect URL Environment Variable

Google

GOOGLE_CLIENT_ID

GOOGLE_CLIENT_SECRET

GOOGLE_REDIRECT_URL

Facebook

FACEBOOK_CLIENT_ID

FACEBOOK_CLIENT_SECRET

FACEBOOK_REDIRECT_URL

Twitter

TWITTER_CLIENT_ID

TWITTER_CLIENT_SECRET

TWITTER_REDIRECT_URL

Configuration

We need to add the configurations to our Laravel application. We will add the details to the config/services.php file. The configurations are as below:

'twitter' => [
    'client_id'     => env('TWITTER_CLIENT_ID'),
    'client_secret' => env('TWITTER_CLIENT_SECRET'),
    'redirect'      => env('TWITTER_REDIRECT_URL')
]

After configurations, we are going to update the user migration file to accommodate Twitter as an authentication provider.

user migration file to accommodate Twitter as an authentication provider.

We will then require the routes/web.php file to factor in Twitter redirect and a callback route.

Route::get('/twitter-redirect', [LoginController::class, 'twitterRedirect']);
Route::get('/twitter-callback', [LoginController::class, 'twitterCallback']);

The first way here will show the Twitter authentication page, whereas the second method is responsible for handling the response once a user authenticates using Twitter as the provider.

To handle the redirect we can add the below logic to the LoginController class:

/**
  * Redirect the user to the Twitter authentication page.
  *
  * @return \Illuminate\Http\Response
  */    
public function twitterRedirect()
{
   return Socialite::driver('twitter')->redirect();
}
The callback login is managed as follows:
  /**
     * Obtain the user information from Twitter.
     *
     * @return \Illuminate\Http\Response
     */
    public function twitterCallback()
    {
        try {
            $user = Socialite::driver('twitter')->user();
        } catch (Exception $e) {
            return redirect('/login');
        }
        // check if they're an existing user
        $existing = User::where('email', $user->email)->first();
        if ($existing) {
            // log the user in
            auth()->login($existing);
        } else {
            // create a new user
            $newUser                 = new User;
            $newUser->name           = $user->name;
            $newUser->email          = $user->email;
            $newUser->twitter_id     = $user->id;
            $newUser->save();
            auth()->login($newUser);
        }
        return redirect()->to('/dashboard');
    }

The last and final step is to add the Twitter button to your login page and point to the relevant route. We have easily and effortlessly configured Facebook authentication to our application.

Hire Experts for Laravel Socialite

Want to integrate Google, Facebook, or Twitter login? Our Laravel experts specialize in Socialite integration, saving you time and ensuring a flawless setup.

Conclusion

We have finally completed the Laravel Login with Google, Facebook and Twitter. Laravel Socialite enables us to add a number of social logins in our application, and it builds a good user experience for users.

Moreover, a user tends to choose social logins because it is easy to manage and secure. Moreover, there are plenty of implementations of Laravel socialite, which includes Laravel Socialite with passport and an Apple authentication are a few we can mention.

We hope this article was able to highlight some light on how to implement social authentication in your application. If you have any queries or concerns then feel free to reach out to us.

FAQ

What is Laravel Socialite, and why should I use it?

Laravel Socialite is a package designed to simplify the implementation of social authentication in Laravel applications. It allows developers to integrate various social login providers like Google, Facebook, Twitter, and more with ease. Using Socialite enhances user experience by providing a quick and secure way for users to log in without needing to create a new account.

How do I install Laravel Socialite in my application?

To install Laravel Socialite, you can use Composer, the PHP package manager. Run the following command in your terminal:

bash

composer require laravel/socialite

After installation, you will need to configure your application with the appropriate credentials for the social platforms you wish to use.

What are the steps to set up Google authentication using Laravel Socialite?

To set up Google authentication, follow these steps:

  • Create a project in the Google Developers Console and obtain your client ID and secret.

  • Update your config/services.php file with the Google credentials.

  • Configure your .env file with the appropriate values.

  • Define routes for redirecting and handling callbacks in your routes/web.php.

  • Implement methods in your LoginController to manage the authentication process.

Can I use multiple social login providers in my application?

Yes, Laravel Socialite supports multiple social login providers simultaneously. You can integrate various providers such as Google, Facebook, Twitter, and others by following similar steps for each provider's setup and configuration.

What should I do if a user encounters issues during social login

If users experience issues during social login, ensure that:

  • The credentials (client ID and secret) are correctly configured in your application.

  • The redirect URLs match those specified in the social platform's developer console.

  • Your application has proper error handling implemented in the callback methods of your controllers to manage exceptions gracefully.

.

Mukesh Ram

Founder and CEO, Acquaint Softtech

I love to make a difference. Thus, I started Acquaint Softtech with the vision of making developers easily accessible and affordable to all. Me and my beloved team have been fulfilling this vision for over 15 years now and will continue to get even bigger and better.

Share this on

Subscribe to new posts

Other Interesting Readings

. Khamma Ghani ‘Jaisalmer’ – A trip to remember!
April 5th, 2018
Khamma Ghani ‘Jaisalmer’ – A trip to remember!

Office trips are always we look up to. This year, Team Acquaint has decided to explore Jaisalmer. In this blog post, we have shared all our memories.

IPL: How Cricket's Biggest League reflects IT outsourcing. IPL: How Cricket's Biggest League reflects IT outsourcing
March 11th, 2024
IPL: How Cricket's Biggest League reflects IT outsourcing

Remote work has become popular in the business landscape. IPL being the biggest cricket league in the world has a lot to offer when talking about how the concept of IT outsourcing relates itself with the league. Read the blog to learn more.

. MVP Chapter #6: How to Build an MVP?
MVP
August 31st, 2022
MVP Chapter #6: How to Build an MVP?

Building your MVP methodically with a proven step-by-step system can result in a fast, reliable, and cost-effective development of your MVP.

Hire Us As Your From Arrow

Technical Partner

Let's Connect

We ensure you’re matched with the right talent resource based on your requirement.