grazulex / laravel-multipersona
Laravel MultiPersona is a lightweight context-layer system for Laravel users. It allows a single user to switch between different roles, accounts, or tenants dynamically, without creating multiple logins or sessions.
Requires
- php: ^8.4
- illuminate/support: ^12.0|^13.0
- nesbot/carbon: ^3.15
Requires (Dev)
- doctrine/dbal: ^4.6
- larastan/larastan: ^3.15
- laravel/pint: ^1.32
- orchestra/testbench: ^10.0|^11.0
- pestphp/pest: ^3.8|^4.7|^5.3
- pestphp/pest-plugin-laravel: ^3.2|^4.1|^5.0
- rector/rector: ^2.9
Suggests
- doctrine/dbal: Required for database operations and migrations
Provides
None
Conflicts
None
Replaces
None
README
Tip
What Laravel MultiPersona does for you โ Let one user act as several personas โ admin and client, company A and company B โ and switch between them without extra logins or sessions. Backend-only, it works with your existing policies and middleware.
This package is free and maintained on my own time. If it saves you hours, a small contribution helps me keep it going: ๐ GitHub Sponsors ยท โ Buy Me a Coffee ยท PayPal
Laravel MultiPersona is a lightweight context-layer system for Laravel users.
Laravel MultiPersona is a lightweight context-layer system for Laravel users.
It allows a single user to switch between different roles, accounts, or tenants dynamically, without creating multiple logins or sessions.
๐ What It Solves
- Switch between "personas" (admin โ client, company A โ company B)
- Contextual permissions and role handling
- No UI or API enforced โ 100% backend, policy, and middleware-driven
๐ฆ Installation
Requirements
- PHP 8.4 or higher
- Laravel 12.x or 13.x
composer require grazulex/laravel-multipersona
๐งฉ Core Concepts
- Persona: A context attached to a user (e.g. company, role, project)
- Active Persona: The currently selected context
- Persona Manager: A service to query, switch, or manipulate personas
- Middleware: Force or apply a persona context
โ Quick Example
// Get current active persona $currentPersona = persona(); // List all user personas $userPersonas = auth()->user()->personas; // Create a new persona $persona = auth()->user()->createPersona([ 'name' => 'Company Admin', 'context' => [ 'role' => 'admin', 'company_id' => 123, 'permissions' => ['read', 'write', 'delete'] ] ]); // Switch to persona auth()->user()->switchToPersona($persona);
The active persona is stored in the database (is_active column), the single source of truth: activating a persona deactivates the user's other personas, and persona(), PersonaManager::current() and $user->activePersona() always return the same persona. The session only keeps a pointer that is kept in sync with the database (see Architecture).
๐งฑ What's Provided
- Trait:
HasPersonasfor yourUsermodel - Data filtering:
BelongsToPersonatrait for your own models: a global scope restricts their queries to the rows of the active persona, on a configurable column (see Usage Guide) - Middleware:
EnsureActivePersona,SetPersonaFromRequest - Helpers:
persona(),personas($user) - Events: Complete event system for persona lifecycle
- Listeners: registered automatically:
LogPersonaSwitch,CachePersonaPermissions(permissions cache) andForgetPersonaPermissions(cache invalidation when the persona changes). Disable with'register_listeners' => false(see Events Guide) - Switch audit (opt-in): with
'audit' => ['enabled' => true], every persona switch (user, date, source and target persona) is recorded in thepersona_switch_logstable through thePersonaSwitchLogmodel, and aPersonaSwitchLoggedevent is dispatched;'log_channel'sends theLogPersonaSwitchentries to a dedicated log channel (see Events Guide) - Gate integration (opt-in): with
'gate' => ['enabled' => true],$user->can(),Gate::allows()and@cangrant the abilities listed in thepermissionsof the active persona;'deny_unlisted' => truealso denies the other abilities while that persona is active (see Usage Guide) - Time-limited personas:
$user->switchToPersonaFor($persona, 600)activates a persona for a limited time; once it has expired, the persona that was active before is activated again and aPersonaExpiredevent is dispatched (see Usage Guide) - Service:
PersonaManagerfor programmatic access - Contract:
PersonaInterfacefor custom implementations
โ What's Not Included
- No routes or controllers
- No CLI or HTTP APIs
- No UI layer โ you choose how to expose it
๐ Complete Documentation
Getting Started
- ๐ Installation Guide - Complete setup instructions
- ๐ Usage Guide - Basic and advanced usage examples
- โก Quick Start Example - Working code examples
Core Features
- ๐ญ Events Guide - Event system and listeners
- ๐ก๏ธ Middleware Guide - Route protection and context
- ๐๏ธ Architecture - System design and components
Advanced Topics
- ๐ฏ Advanced Patterns - Multi-tenant, role hierarchy, delegation
- ๐ Frontend Integration - Vue.js, React, Alpine.js examples
- ๐ API Reference - Complete method documentation
Use Cases
- Multi-tenant SaaS: Users switch between different company contexts
- Role-based Access: Same user, different permissions per context
- Agency Management: Manage multiple client accounts
- Marketplace Platforms: Buyer/seller context switching
- Enterprise Systems: Department or project-based access
๐ฏ Real-World Examples
Multi-tenant Application
// User switches between companies $companyA = $user->createPersona([ 'name' => 'Acme Corp Admin', 'context' => [ 'company_id' => 1, 'role' => 'admin', 'permissions' => ['manage_users', 'view_reports'] ] ]); $companyB = $user->createPersona([ 'name' => 'TechStart User', 'context' => [ 'company_id' => 2, 'role' => 'user', 'permissions' => ['view_dashboard'] ] ]);
Filter the data of each company with the BelongsToPersona trait. Its global scope restricts every query on the model to the rows of the active persona:
use Grazulex\LaravelMultiPersona\Traits\BelongsToPersona; class Invoice extends Model { use BelongsToPersona; // Compare invoices.company_id with the company_id of the persona context public function getPersonaColumn(): string { return 'company_id'; } public function getPersonaContextKey(): ?string { return 'company_id'; } } $user->switchToPersona($companyA); Invoice::all(); // invoices of company 1 only Invoice::create(['total' => 100]); // company_id is set to 1 $user->switchToPersona($companyB); Invoice::all(); // invoices of company 2 only Invoice::withoutPersonaScope()->get(); // no filter Invoice::forPersona($companyA)->get(); // another persona
Without overrides, the trait compares the persona_id column with the ID of the active persona. The column, the context key and the behaviour without active persona are set in the scope section of config/multipersona.php. When no persona is active, queries are not filtered by default: set 'scope' => ['strict' => true] to return no row instead, or protect the routes with the EnsureActivePersona middleware.
Time-limited Persona
// The user works as "Standard User" and needs the admin persona for 10 minutes $user->switchToPersona($standard); $user->switchToPersonaFor($admin, 600); // seconds, DateInterval or date persona()->getName(); // "Admin" app('multipersona')->expiresAt(); // Carbon instance, 10 minutes from now // 10 minutes later, on the next request persona()->getName(); // "Standard User"
Without duration, 'temporary' => ['ttl' => 900] (seconds) of config/multipersona.php is used. The expiration is stored in the personas table (run php artisan migrate after upgrading) and applied whenever the active persona is read. To also release the personas of users who make no request, schedule PersonaManager::releaseExpired():
Schedule::call(fn () => app('multipersona')->releaseExpired())->everyMinute();
Middleware Protection
// Protect routes requiring specific roles Route::middleware(['auth', 'persona.required', 'role:admin'])->group(function () { Route::get('/admin/dashboard', [AdminController::class, 'dashboard']); });
Frontend Integration
<!-- Vue.js component --> <PersonaSelector :current-persona="currentPersona" :available-personas="availablePersonas" @persona-changed="handlePersonaChange" />
๐งช Testing
The package includes comprehensive test coverage:
composer test
Current test metrics:
- 58 tests across Unit, Feature, Integration, and Listeners
- 87% code coverage
- 149 assertions ensuring reliability
๐ค Contributing
We welcome contributions! See our Contributing Guide for details.
Development Setup
git clone https://github.com/grazulex/laravel-multipersona.git cd laravel-multipersona composer install composer test
๐ Security
If you discover any security vulnerabilities, please review our Security Policy.
๐ Support This Package
Laravel MultiPersona is free, open source and maintained on my own time. If it saves you hours, here is how you can give back:
- โญ Star the repository โ it helps other developers find it
- ๐ฆ Share it with your team and network
- ๐ Sponsor on GitHub, buy me a coffee or donate via PayPal โ every contribution funds maintenance, new features and Laravel upgrades
๐ License
Laravel MultiPersona is open-sourced software licensed under the MIT license.
Made with โค๏ธ for the Laravel community
๐ Documentation โข ๐ Report Issues โข ๐ฌ Discussions
