audunru / social-accounts
Add social login to your Laravel app
Requires
- php: ^8.3
- laravel/framework: ^13.0
- laravel/socialite: ^5.0
- spatie/laravel-package-tools: ^1.9
Requires (Dev)
- fakerphp/faker: ^1.12
- laravel/pint: ^1.0
- mockery/mockery: ^1.3
- orchestra/testbench: ^11.0
- php-coveralls/php-coveralls: ^2.2
- phpmd/phpmd: ^2.10
- phpunit/phpunit: ^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-main
- v13.x-dev
- v11.1.2
- v11.1.1
- v11.1.0
- v11.0.0
- v10.2.0
- v10.1.0
- v10.0.0
- v9.2.1
- v9.2.0
- v9.1.4
- v9.1.3
- v9.1.2
- v9.1.1
- v9.1.0
- v9.0.0
- v8.1.2
- v8.1.1
- v8.1.0
- v8.0.0
- v7.0.0
- v6.1.2
- v6.1.1
- v6.1.0
- v6.0.1
- v6.0.0
- v5.0.0
- v4.0.0
- v3.1.0
- v3.0.0
- v2.0.0
- v1.0.0
- v0.5.2
- v0.5.1
- v0.5.0
- v0.4.0
- v0.3.0
- v0.2.1
- v0.2.0
- v0.1.1
- v0.1.0
- dev-fix/redirect-backslash
- dev-remove-lock
This package is auto-updated.
Last update: 2026-11-13 22:05:07 UTC
README
Add social login (Google, Facebook, and others) to your Laravel app.
This package uses Laravel Socialite to authenticate users, and takes care of storing the provider (eg. Google) and provider user ID (eg. 123456789) as a SocialAccount (a related model of the User model).
Your users can add one or more social logins to their account. It's up to you if you want them to sign up with a normal username and password first, or if they can sign up just by signing in with a provider.
The package also has a JSON API so you can display which social accounts a user has logged in with, and allow them to remove them.
Upgrading from earlier versions
Notable changes are documented in the migration guide.
Installation
Step 1: Install with Composer
composer require audunru/social-accounts
Step 2: Make changes to your code
Add the HasSocialAccounts trait to your User model:
use audunru\SocialAccounts\Traits\HasSocialAccounts; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasSocialAccounts; /** * Get user who has logged in with Google account ID 123456789 * $user = User::findBySocialAccount('google', '123456789') * * Retrieve all social accounts belonging to $user * $user->socialAccounts */ }
Second, you need to specify which providers you are going to support. Publish the configuration, and open up config/social-accounts.php and add them to the array.
php artisan vendor:publish --tag=social-accounts-config
There is an array called "providers" where you can specify the ones you want:
'providers' => [ // 'bitbucket', // 'facebook', // 'github', // 'gitlab', 'google', // 'linkedin', // 'twitter', ],
Third, you need to add credentials for your supported social login providers to config/services.php. To login with Google, you would add the following to config/services.php:
'google' => [ 'client_id' => env('GOOGLE_CLIENT_ID'), // Get your client ID and secret from https://console.developers.google.com 'client_secret' => env('GOOGLE_CLIENT_SECRET'), // Note: The "redirect" setting will be configured automatically. You are not required to add it to services.php yourself. If you don't want to use this package's default routes, you will need to configure it. If so, the package will use the value from services.php. // 'redirect' => '/social-accounts/login/google/callback', ],
Step 3: Configuration and customization
You can find the configuration and documentation of all options in config/social-accounts.php.
Step 4: Run migrations
php artisan vendor:publish --tag=social-accounts-migrations php artisan migrate
The migrations will create a social_accounts table, which will hold all added social accounts.
If you set the "automatically_create_users" option in config/social-accounts.php to true, the email and password columns in your users table will be made nullable. Not all providers require users to have an email address, and the password column must be nullable because users who sign up this way won't have password.
Usage
Adding social login to existing users
If you want to allow your existing users to log in with Google, add a link to /social-accounts/login/google somewhere in your application:
@auth <a href="/social-accounts/login/google">Add Google login to my account</a> @endauth
After clicking on this link, the user will be redirected to Google, where they must authorize the request. Afterwards they will be returned to your app. Then, a new SocialAccount model will be added as related model of the User.
If the provider account already belongs to another user, the callback throws audunru\SocialAccounts\Exceptions\SocialAccountBelongsToAnotherUser (HTTP 409). The logged-in user does not change, and no social account is added. You can render the exception in bootstrap/app.php, for example:
use audunru\SocialAccounts\Exceptions\SocialAccountBelongsToAnotherUser; use Illuminate\Foundation\Configuration\Exceptions; ->withExceptions(function (Exceptions $exceptions) { $exceptions->render(function (SocialAccountBelongsToAnotherUser $e) { return redirect()->intended('/')->with('error', 'This social login belongs to another user.'); }); })
Signing up users
If you want to allow users to sign up with this package, you must first publish the configuration file and then set automatically_create_users to true.
'automatically_create_users' => true,
Then, run the migrations so that the email and password columns are made nullable.
php artisan migrate
Then add a link to /social-accounts/login/google:
<a href="/social-accounts/login/google">Sign up with Google</a>
The new user gets the email address that the provider returns. Some providers do not verify email addresses, so a person can create a user with the email address of another person. To allow only verified email addresses, define a create-user-with-provider gate (see Gates). If a user with the same email address already exists (the comparison ignores case), the callback throws audunru\SocialAccounts\Exceptions\EmailAlreadyRegistered (HTTP 409). No user is created, and the provider account is not linked to the existing user. You can render the exception in the same way as SocialAccountBelongsToAnotherUser (see Adding social login to existing users). If the create-user-with-provider gate denies, the callback throws audunru\SocialAccounts\Exceptions\UserCreationDenied (HTTP 403). You can render this exception in the same way.
Logging in
For users who are not signed in, simply add a link to /social-accounts/login/google:
<a href="/social-accounts/login/google">Sign in with Google</a>
Remember Me
Add "remember" to the login URL to keep the user signed in:
<a href="/social-accounts/login/google?remember">Sign in with Google</a>
Redirect after login
Add "redirect=/some-url" to the login URL to redirect the user after login:
<a href="/social-accounts/login/google?redirect=/some-url" >Sign in with Google</a >
Only relative URLs are supported: the value must start with /, but not with // or /\, and must not contain control characters (for example tabs or newlines). Other values are ignored. The redirect applies only to this login. If the callback fails, the intended URL is still available to your exception handler, and the package removes it after that request.
API
The JSON API, which by default is accessible at /social-accounts, allows authenticated users to retrieve their social accounts and remove them.
To retrieve an array of social accounts, make a GET request to /social-accounts.
To retrieve a single social account, make a GET request to /social-accounts/123, where 123 is the ID of the account.
To delete a social account, make a DELETE request to /social-accounts/123.
Users can't update social accounts through the API, they will have to delete them first and then authorize again.
Optional Parameters, Access Scopes and Stateless Authentication
To include optional parameters in the request, call the registerProviderSettings method on the facade. The method takes three parameters, the provider name, the name of the method to call on the provider object, and an array of parameters.
For example, you can use this to limit the domains a Google user can choose to sign in with to just one:
SocialAccounts::registerProviderSettings('google', 'with', ['hd' => 'seinfeld.com']);
Gates
You can use gates to allow or deny certain actions. Gates should be defined within the boot method of your AppServiceProvider.
<?php namespace App\Providers; use App\User; use audunru\SocialAccounts\SocialAccounts; use Laravel\Socialite\Contracts\User as ProviderUser; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Register any authentication / authorization services. */ public function boot() { /* * If your company uses G Suite and you want to ensure that only employees can log in, you can define a "login-with-provider" gate. * * If you don't define this gate, any ProviderUser is allowed to pass through. */ Gate::define('login-with-provider', function (?User $user, ProviderUser $providerUser) { /* * $providerUser->user['hd'] contains the domain name the Google account belongs to. * * It's good practice to verify that the account does in fact belong to your company after the user has authorized with Google and returned to your application. */ return 'company.com' === $providerUser->user['hd']; }); /* * If you want to restrict who can add social accounts, you can define a "add-social-account" gate. * * If you don't define this gate, any authenticated user can add a social account. */ Gate::define('add-social-account', function (User $user, ProviderUser $providerUser) { /* * isAdmin() is a hypothetical method you could define on your User model. * * In this case, only administrators would be allowed to add social accounts. */ return $user->isAdmin(); }); /* * If "automatically_create_users" is true, you can define a "create-user-with-provider" gate. It runs only before a new user is created. * * If you don't define this gate, any ProviderUser that is not linked to a user can sign up. */ Gate::define('create-user-with-provider', function (?User $user, ProviderUser $providerUser) { /* * $providerUser->user['email_verified'] tells if Google verified the email address. * * The first argument is always null, because the user is not logged in. It must be nullable, else the gate denies the request. */ return $providerUser->user['email_verified'] ?? false; }); } }
Events
When a user is created after authenticating with a provider, a SocialUserCreated event is dispatched. The event receives the User, SocialAccount and ProviderUser model.
When a social account is added to an existing user, a SocialAccountAdded event is dispatched. The event receives the User, SocialAccount and ProviderUser model.
When a user removes a social account through the API, a SocialAccountRemoved event is dispatched after the delete. The event receives the User model, the provider name and the provider user ID. It does not receive the SocialAccount model, because the social account is already deleted, and a queued listener could not load it again. It is not dispatched when the policy denies the request or when the delete fails.
After each successful login with a provider, a SocialUserLoggedIn event is dispatched. The event receives the User, the provider name and the ProviderUser model. It is dispatched also when the user was already logged in with the same provider account, and also when a user is created in the same request. It is not dispatched when a logged-in user adds a new social account, because the user did not log in with an account that they already had. Then the callback does not call Auth::login() (so Laravel's Login event is not dispatched either), and only SocialAccountAdded is dispatched. Thus a user who has no social account with the provider must first add one, and then log in with it, before the login counts as a provider login. It is not dispatched when the callback fails (the provider returns an error, or the response is 401, 403 or 409). Use it to record the time of the last provider login, for example when a user must authenticate with the provider again before a sensitive action. The event is dispatched after Auth::login(), so a listener can write to the session.
For instance, you could listen for an event and grab more details about the user.
<?php namespace App\Listeners; use audunru\SocialAccounts\Events\SocialUserCreated; class AddUserAvatar { /** * Handle the event. * * @param SocialUserCreated $event * @return void */ public function handle(SocialUserCreated $event) { /* * The package only saves the user's name and email when creating a new user. * * By listening for the event, we can grab more details about the user. */ $event->user->update([ 'avatar' => $event->providerUser->getAvatar(); ]); } }
Development
Testing
Run tests:
composer test