7 min read

How to implement social login in Laravel

We will be using the following Laravel environment:

  • Laravel 9.x
  • PHP 8.1
  • Jetstream/Breeze with teams
  • Fortify
  • Socialite
  • Pest

Summary

  • Install Laravel\Socialite
  • Create a social users table: database/migrations/create_social_user_table.php
  • Create a social user model: App/Models/SocialUser.php
  • Add required Oauth services: config/services.php
  • Create a social login route with callback: routes/web.php
  • Create handlers for login and callback routes: App/Http/Controller/Auth/SocialLoginController.php
  • Make a method public: App/Actions/Fortify/CreateNewUser.php
  • Create tests: test/Feature/SocialLoginTest.php

Install Socialite

           composer install Laravel\Socialite
        

Implementation

  • we want a user to be able to login by email and/or one or more social providers
  • the user should be granted access to the same account when social details matches an existing user
  • a personal team should be created for new accounts
  • test new, existing and multiple social accounts

Explorer: blog.seanwhite.dev

                               use Illuminate\Database\Migrations\Migration;
                   use Illuminate\Database\Schema\Blueprint;
                   use Illuminate\Support\Facades\Schema;
                   
                   return new class extends Migration
                   {
                       public function up()
                       {
                           Schema::create('social_user', function (Blueprint $table) {
                               $table->id();
                               $table->unsignedBigInteger('user_id')->nullable();
                               $table->string('provider');
                               $table->string('provider_user_id');
                               $table->string('email');
                               $table->string('name');
                               $table->string('avatar')->nullable();
                               $table->timestamps();
                   
                               $table->unique(['provider', 'provider_user_id']);
                           });
                       }
                   };
                            

                  7 files found

                  php

                  Something to consider…

                  You might want to change the login.social route to a POST request when initiating the login flow.