Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Impersonate Ui Laravel Package

hapidjus/laravel-impersonate-ui

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require hapidjus/laravel-impersonate-ui
    
  2. Add the Trait to Your User Model Ensure your App\Models\User (or equivalent) includes:

    use Lab404\Impersonate\Models\Impersonate;
    use Hapidjus\ImpersonateUI\Traits\ImpersonateUI;
    
    class User extends Authenticatable
    {
        use Notifiable, Impersonate, ImpersonateUI;
    }
    
  3. Publish Assets Run:

    php artisan vendor:publish --tag=config --tag=view
    
    • Config: config/impersonate-ui.php
    • Blade views: resources/views/vendor/impersonate-ui/
  4. Add Middleware Register the impersonate middleware in app/Http/Kernel.php:

    'web' => [
        // ...
        \Hapidjus\ImpersonateUI\Middleware\ImpersonateUI::class,
    ],
    
  5. First Use Case

    • Visit any page as an authorized user (e.g., /admin/dashboard).
    • A new UI button/panel will appear (default: top-right dropdown).
    • Click to search/select a user to impersonate.

Implementation Patterns

Core Workflow

  1. User Selection

    • The UI provides a searchable dropdown (via Blade + JavaScript) to filter users by name, email, or custom fields.
    • Example: Add a custom search field in config/impersonate-ui.php:
      'search_fields' => ['name', 'email', 'username'],
      
  2. Integration with Existing UI

    • Dropdown Integration: Add the Blade directive to your layout (e.g., resources/views/layouts/app.blade.php):
      @impersonateUI
      
    • Modal Integration: Trigger the modal via JavaScript:
      window.impersonateUI.open();
      
  3. Role-Based Access Restrict impersonation to specific roles in the config:

    'users_allowed' => ['admin@example.com', 'supervisor@example.com'],
    

    Or dynamically via middleware:

    public function handle($request, Closure $next)
    {
        if (!auth()->user()->isAdmin()) {
            abort(403);
        }
        return $next($request);
    }
    
  4. Customizing the UI

    • Override the default Blade views in resources/views/vendor/impersonate-ui/.
    • Extend the search functionality by publishing and modifying the JavaScript:
      php artisan vendor:publish --tag=js
      
      Then update public/vendor/impersonate-ui/js/impersonate-ui.js.
  5. Logging and Auditing Track impersonation events by extending the Impersonate trait:

    protected static function bootImpersonate()
    {
        parent::bootImpersonate();
        static::impersonating(function ($user, $impersonator) {
            \Log::info("User {$impersonator->email} impersonated as {$user->email}");
        });
    }
    

Gotchas and Tips

Common Pitfalls

  1. Middleware Placement

    • Issue: Impersonate UI not appearing.
    • Fix: Ensure the ImpersonateUI middleware is registered after auth middleware in Kernel.php:
      'web' => [
          \App\Http\Middleware\Authenticate::class,
          \Hapidjus\ImpersonateUI\Middleware\ImpersonateUI::class,
      ],
      
  2. Debug Mode Dependency

    • Issue: UI disappears in production (APP_DEBUG=false).
    • Fix: Explicitly enable it in config:
      'enabled' => env('IMPERSONATE_UI_ENABLED', false),
      
      Then set in .env:
      IMPERSONATE_UI_ENABLED=true
      
  3. User Model Mismatch

    • Issue: "Class not found" errors for Impersonate trait.
    • Fix: Verify the trait is added to the correct User model (e.g., App\Models\User, not App\User).
  4. JavaScript Conflicts

    • Issue: Search dropdown not working.
    • Fix: Ensure jQuery is loaded before the impersonate UI script. Publish and modify the JS if needed:
      php artisan vendor:publish --tag=js
      
  5. Permission Denied

    • Issue: UI appears but impersonation fails with 403.
    • Fix: Check users_allowed in config or implement custom authorization logic in the middleware.

Pro Tips

  1. Dynamic User Filtering Override the getImpersonateUIUsers method in your User model:

    public function getImpersonateUIUsers()
    {
        return self::where('is_active', 1)->get();
    }
    
  2. Localization Translate UI strings by publishing the language files:

    php artisan vendor:publish --tag=lang
    

    Then add translations to resources/lang/{locale}/impersonate-ui.php.

  3. Impersonation Depth Limit nested impersonation by extending the Impersonate trait:

    protected static function bootImpersonate()
    {
        parent::bootImpersonate();
        static::impersonating(function ($user, $impersonator) {
            if ($impersonator->isImpersonating()) {
                abort(403, 'Nested impersonation not allowed.');
            }
        });
    }
    
  4. Testing Use the Impersonate facade in tests:

    use Lab404\Impersonate\Facades\Impersonate;
    
    public function test_impersonation()
    {
        Impersonate::impersonate(User::find(1));
        $this->assertAuthenticatedAs(User::find(1));
    }
    
  5. Performance For large user bases, eager-load relationships in getImpersonateUIUsers:

    public function getImpersonateUIUsers()
    {
        return self::with('roles')->whereHas('roles', function($q) {
            $q->where('name', '!=', 'banned');
        })->get();
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope