Search by

grazulex / laravel-multipersona

Grazulex

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.

v1.7.1 2026-12-02 03:09 UTC

This package is auto-updated.

Last update: 2026-12-02 03:09:49 UTC


README

Laravel MultiPersona

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.

Latest Version Total Downloads License PHP Version Laravel Version Tests Code Style

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: HasPersonas for your User model
  • Data filtering: BelongsToPersona trait 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) and ForgetPersonaPermissions (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 the persona_switch_logs table through the PersonaSwitchLog model, and a PersonaSwitchLogged event is dispatched; 'log_channel' sends the LogPersonaSwitch entries to a dedicated log channel (see Events Guide)
  • Gate integration (opt-in): with 'gate' => ['enabled' => true], $user->can(), Gate::allows() and @can grant the abilities listed in the permissions of the active persona; 'deny_unlisted' => true also 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 a PersonaExpired event is dispatched (see Usage Guide)
  • Service: PersonaManager for programmatic access
  • Contract: PersonaInterface for 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

Core Features

Advanced Topics

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