Download the PHP package chuoke/laravel-user-identities without Composer
On this page you can find all versions of the php package chuoke/laravel-user-identities. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download chuoke/laravel-user-identities
More information about chuoke/laravel-user-identities
Files in chuoke/laravel-user-identities
Package laravel-user-identities
Short Description Multi-auth identities for Laravel: decouple auth data from your users table.
License MIT
Informations about the package laravel-user-identities
Laravel User Identities
A flexible and extensible authentication system for Laravel that enables multiple identity types per user, supporting password-based, OAuth, and token authentication methods.
Core Philosophy
Keep your users table lean - Move authentication data out of users table and into a dedicated identities table. This approach:
- Separates Concerns - User data stays clean, auth data stays organized
- Improves Performance - User queries remain fast, auth queries are optimized
- Enables Flexibility - Add new auth methods without touching users table
- Better Analytics - Clear separation of authentication methods per user
- Enhanced Security - Minimize sensitive data exposure in user queries, logs, and debugging
Features
- 🎯 Separation of Concerns: Decouple authentication data from user business data
- 🔄 Highly Extensible: Easy to add new identity types without schema changes
- ✅ Independent Verification: Track verification status for each identity separately
- 🛡️ Secure by Default: Automatic password hashing and credential protection
- 🔌 Laravel Integration: Custom UserProvider for seamless authentication with default guards
- ⚡ Performance Optimized: Smart caching to minimize database queries
- 🔐 Remember Me: Token stored in identities table, no
remember_tokencolumn needed on users - 🔑 Two-Factor Auth: Fortify 2FA bridge — stores secret & recovery codes as identity, zero user columns
- 🌐 Socialite Ready: One-line OAuth identity binding from Socialite callbacks
- 🔁 Password Rehash: Automatic bcrypt rehash support for Laravel 11+
Installation
Publish configuration and migrations:
Quick Start
1. Add Traits to User Model
Option A: Extend the package's base User class
Option B: Add traits to your existing User model (recommended)
2. Configure Laravel Auth
Note: No custom guard driver is needed. Laravel's built-in
SessionGuardworks perfectly with theuser-identityprovider. All identity-specific logic (credential mapping, lookup, validation, remember-me, rehash) is handled entirely in the provider layer.
3. Create Identities
4. Authenticate Users
Fortify Integration
This package is designed to work with Laravel Fortify with minimal configuration. The IdentityUserProvider speaks the same credential dialect as Fortify out of the box.
Login (Zero Changes Required)
Fortify calls Auth::attempt(['email' => ..., 'password' => ...]) internally. The credential_field_mapping config maps email → identity type email, so no Fortify customization is needed for standard login.
To allow login by username instead of (or in addition to) email, just add 'username' => 'username' to the mapping and Fortify's login form works automatically.
Password Confirmation — ConfirmPassword Action
Fortify's default password confirmation checks the configured Fortify username field on the user model. If you keep auth fields out of the users table, register the package action explicitly:
Note for OAuth-only users: If a user has no password-based identity (e.g. signed up via GitHub only), the confirm-password check will always fail. This is correct security behaviour — these users have no password to confirm. You should redirect them or provide an alternative confirmation flow.
Registration — UserIdentityCreate Action
UserIdentityCreate is a general create action, not a Fortify contract implementation. For
registration, keep Fortify's CreatesNewUsers implementation in your application and call the
package action after creating the authenticatable:
The package does not provide Fortify's CreatesNewUsers implementation because the authenticatable
model and user attributes are application-specific. Your app decides whether it is creating a
User, Admin, or another authenticatable model, then calls UserIdentityCreate for the identities
it needs.
Email Verification — MustVerifyEmail Trait
The package ships a MustVerifyEmail trait that reads the email address and verification status from the email identity record rather than from user model columns:
Fortify's email verification pipeline (VerifyEmailResponse, VerificationController) works without modification. When the user clicks the verification link, call:
Change Password
Fortify does not ship a built-in UpdateUserPassword action; applications provide their own
implementation of UpdatesUserPasswords. Keep that action in your application and call the package
password action after validation:
Password Reset — ResetUserPassword Action
Add CanResetPassword to your User model so Fortify can send reset links:
Then call the package password action from your application's reset action:
Profile Information
Fortify does not ship a built-in UpdateUserProfileInformation action; applications provide their
own implementation of UpdatesUserProfileInformation. Keep that action in your application because
profile fields are business-specific. When a profile update should also update an identity, call the
package identity actions from your app action:
Two-Factor Authentication — HasTwoFactorIdentity Trait
Fortify 2FA is never enabled by this package. Enable Fortify's two-factor feature only in your
application's config/fortify.php when you want it.
When enabled, HasTwoFactorIdentity lets Fortify 2FA work without any additional columns on the
users table:
Fortify's 2FA controllers type-hint Fortify's concrete action classes instead of contracts. The
package 2FA actions replace those concrete classes and directly manage the two_factor record in
user_identities: enabling creates or updates the identity, confirming marks it verified,
disabling deletes it, and regenerating recovery codes updates its JSON credentials.
Bind them explicitly in your application's service provider:
The HasTwoFactorIdentity trait provides Eloquent attribute accessors that intercept Fortify's access to two_factor_secret, two_factor_recovery_codes, and two_factor_confirmed_at, storing all data as a single identity record:
| Fortify expects (user column) | Stored as (identity) |
|---|---|
two_factor_secret |
type='two_factor' credential JSON .secret |
two_factor_recovery_codes |
type='two_factor' credential JSON .recovery_codes |
two_factor_confirmed_at |
type='two_factor' identity verified_at |
The trait also listens for Fortify's TwoFactorAuthenticationDisabled event when Fortify is
installed. This lets Fortify's default disable action remove the two_factor identity instead of
leaving an empty identity record behind.
For a more explicit Fortify integration, the package also ships optional replacements for Fortify's
concrete 2FA actions. They are not required, but they are useful when you want the action code itself
to directly manage UserIdentity records or serve as sample code:
Zero new columns on users table. Zero new columns on identities table.
Minimal FortifyServiceProvider Wiring
Socialite Integration
Bind OAuth identities from Socialite callbacks with minimal code:
Stored credential data includes token, refresh_token, expires_in, nickname, avatar, email, and name.
Sanctum Compatibility
Sanctum uses its own personal_access_tokens table and does not add columns to the users table. It is fully compatible with this package out of the box — no special configuration needed.
If you want unified identity querying (list all auth methods including Sanctum tokens), you can register a custom SanctumTokenIdentityType that syncs Sanctum tokens as identities.
Migrating Existing Projects
Optional Global Uniqueness
The package only enforces identity uniqueness within each authenticatable. This allows internal
identity types such as two_factor and _remember_token to reuse fixed identifiers for every user.
Applications that use email addresses, usernames, mobile numbers, or OAuth provider IDs for login should decide which identity types must be unique across all authenticatables and add an application-level database constraint. On MySQL, a nullable generated column can provide a conditional unique index while excluding internal identity types:
MySQL permits multiple NULL values in a unique index, so excluded types remain unique only within
their owner through the package's default user_identities_unique constraint. Other database
engines may require a partial unique index or an engine-specific equivalent. Resolve existing
duplicates before adding the index.
Before deploying the constraint, audit the selected types for existing duplicates. Creating the index will fail rather than discard or merge conflicting identities:
Adding a stored generated column and index may lock or rebuild a large table. Plan the migration using the online DDL or maintenance-window strategy appropriate for your MySQL deployment.
If upgrading from a package version whose published base migration used
user_identities_global_unique for every identity type, add an application migration that drops
that index and restores the package's owner-scoped constraint before adding any application-level
conditional index:
If your project already has email, password, remember_token on the users table, you can migrate to this package without downtime.
Step 1: Enable Fallback Mode
With fallback enabled, the package reads from identities when available, but gracefully falls back to user model columns (password, remember_token) when no identity record exists. Your app works exactly as before.
Step 2: Run Data Migration
The migrator copies existing password hashes directly — no re-hashing, no user disruption.
Step 3: Disable Fallback
Once all users are migrated, disable fallback:
Step 4 (Optional): Remove Old Columns
Hybrid Mode: Keeping Fields on Users Table
Some fields like email are used very frequently for display, search, and notifications. You may want to keep them on the users table while still using identities for auth.
Setup
How Sync Works
| Action | Effect |
|---|---|
| Identity email updated | users.email auto-synced |
$user->email = 'new@...' then save() |
Identity identifier auto-synced |
| Manual bulk sync | $user->syncAllIdentitiesToUser() |
| Initial setup from user fields | $user->syncAllUserFieldsToIdentities($password) |
Recommended Architecture
This gives you the best of both worlds:
- ⚡
User::where('email', ...)works fast (no join needed) - 🔒 Auth data is cleanly separated
- 🔄 Data stays consistent automatically
Architecture
Identity Type Hierarchy
Database Schema
The package uses a single user_identities table, keeping your users table clean:
What lives in identities (not users table):
| Capability | Identity type | Stored in |
|---|---|---|
| Email login | email |
identifier + hashed password |
| Mobile login | mobile |
identifier + hashed password |
| Username login | username |
identifier + hashed password |
| OAuth (GitHub, etc.) | github |
provider ID + token JSON |
| API key | api_key |
key name + encrypted secret |
| Remember me token | _remember_token |
system token |
| 2FA secret + codes | two_factor |
JSON credentials |
Core Components
- Traits:
HasIdentities,HasIdentityAuth,HasTwoFactorIdentity,SyncsIdentityFields - Models:
UserIdentity- Main model for identity records - Actions:
UserIdentityCreate,UserIdentityFindOrCreateFromSocialite,UserIdentitySocialiteBind,UserIdentityUpdate,UserIdentityVerify,UserIdentityDelete,UserIdentityPasswordUpdate,MigrateUserToIdentities - Auth:
IdentityUserProvider- Custom user provider with remember-me, rehash, and credential mapping support - Types: Hierarchical identity type classes with built-in behaviors
- Events:
IdentityCreated,IdentityUpdated,IdentityDeleted,IdentityVerified - Processors:
HashCredentialProcessor,EncryptCredentialProcessor,PlainCredentialProcessor
Events
All identity lifecycle operations dispatch events:
| Action | Event |
|---|---|
| Create identity | IdentityCreated |
| Update identity | IdentityUpdated (with $changes array) |
| Delete identity | IdentityDeleted |
| Verify identity | IdentityVerified |
Configuration
Requirements
- PHP >= 8.1
- Laravel >= 12.0
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
For detailed API documentation, check the inline code comments in the source files.