PHPackages                             cdoebler/laravel-user-switcher - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. cdoebler/laravel-user-switcher

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

cdoebler/laravel-user-switcher
==============================

Laravel package for fast user switching based on the generic user switcher package.

v1.0.0(4mo ago)02MITPHPPHP ^8.2CI passing

Since Dec 31Pushed 2mo agoCompare

[ Source](https://github.com/cdoebler/laravel-user-switcher)[ Packagist](https://packagist.org/packages/cdoebler/laravel-user-switcher)[ RSS](/packages/cdoebler-laravel-user-switcher/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (10)Versions (2)Used By (0)

Laravel User Switcher
=====================

[](#laravel-user-switcher)

> **⚠️ DEVELOPMENT TOOL - NOT FOR PRODUCTION USE ⚠️**
>
> This package is designed for **local development and staging environments only**. It allows developers to quickly switch between user accounts for testing and debugging purposes.
>
> **DO NOT enable this package in production environments** unless you have a specific, well-understood use case and have implemented additional security measures.

This package provides [Laravel](https://laravel.com) integration for the [Generic User Switcher](https://github.com/cdoebler/php-generic-user-switcher) library. It includes a user provider implementation that fetches users from your Laravel database and an impersonator implementation using Laravel's session and authentication system.

Features
--------

[](#features)

- **Seamless Integration**: Automatically binds `UserProviderInterface` and `ImpersonatorInterface` to Laravel implementations.
- **Configurable**: Easily configure which User model to use.
- **Environment Control**: Restrict user switching to specific environments (e.g., `local`, `staging`) to prevent accidents in production.
- **Session-based Impersonation**: Securely impersonates users by maintaining the original user's ID in the session.

Installation
------------

[](#installation)

Install as a development dependency:

```
composer require cdoebler/laravel-user-switcher --dev
```

For staging environments that use production dependencies, install normally:

```
composer require cdoebler/laravel-user-switcher
```

The service provider is auto-discovered by Laravel.

⚠️ Enable Only in Development
-----------------------------

[](#️-enable-only-in-development)

The package is **disabled by default**. Enable it in your development `.env`:

```
USER_SWITCHER_ENABLED=true
```

Configuration
-------------

[](#configuration)

### Publish Configuration

[](#publish-configuration)

Publish the configuration file to `config/user-switcher.php` using the following command:

```
php artisan vendor:publish --provider="Cdoebler\LaravelUserSwitcher\Providers\UserSwitcherServiceProvider" --tag="config"
```

### Options

[](#options)

The configuration file allows you to customize the package behavior.

OptionDescriptiondefault`user_model`The Eloquent model class for your users.`App\Models\User``enabled`master switch to enable/disable the functionality.`env('USER_SWITCHER_ENABLED', false)``environments`Comma-separated list of allowed environments.`env('USER_SWITCHER_ENVIRONMENTS', 'local,testing')``auto_inject`Automatically inject the switcher widget into rendered pages.`env('USER_SWITCHER_AUTO_INJECT', true)``authorization_callback`Callback function to determine if user switching is allowed.`null`### Environment Variables

[](#environment-variables)

```
USER_SWITCHER_ENABLED=true
USER_SWITCHER_ENVIRONMENTS="local,testing"
USER_SWITCHER_AUTO_INJECT=true
```

Usage
-----

[](#usage)

This package is intended to be used with the **Generic User Switcher** frontend or logic. Once installed, it handles the backend logic for:

1. **Retrieving Users**: It uses your configured Eloquent model to list available users for switching.
2. **Impersonation**: It handles the `loginUsingId` logic and stores the original user in the session to allow switching back.

### Programmatic Usage

[](#programmatic-usage)

If you need to use the interfaces directly in your code, you can inject them:

```
use Cdoebler\GenericUserSwitcher\Interfaces\UserProviderInterface;
use Cdoebler\GenericUserSwitcher\Interfaces\ImpersonatorInterface;

public function index(UserProviderInterface $userProvider, ImpersonatorInterface $impersonator)
{
    // Get all users
    $users = $userProvider->getUsers();

    // Check if currently impersonating
    if ($impersonator->isImpersonating()) {
        // ...
    }
}
```

Authorization
-------------

[](#authorization)

By default, user switching is disabled (`enabled` defaults to `false`) and restricted to `local` and `testing` environments. You can customize this using the `enabled` and `environments` config options, or implement custom authorization logic using the `authorization_callback` configuration option.

### Using Authorization Callback

[](#using-authorization-callback)

The `authorization_callback` allows you to define custom logic to determine whether user switching should be allowed. This is useful when you want to restrict switching based on user roles, permissions, or other criteria.

#### Example: Only Allow Admins to Switch Users

[](#example-only-allow-admins-to-switch-users)

```
// config/user-switcher.php

return [
    // ... other config options

    'authorization_callback' => function (\Illuminate\Http\Request $request) {
        // Only allow switching if the authenticated user is an admin
        return $request->user()?->isAdmin() ?? false;
    },
];
```

#### Example: Check User Permission

[](#example-check-user-permission)

```
// config/user-switcher.php

return [
    // ... other config options

    'authorization_callback' => function (\Illuminate\Http\Request $request) {
        // Check if user has the 'switch-users' permission
        return $request->user()?->can('switch-users') ?? false;
    },
];
```

#### Example: Combine Environment and Role Checks

[](#example-combine-environment-and-role-checks)

```
// config/user-switcher.php

return [
    // ... other config options

    'authorization_callback' => function (\Illuminate\Http\Request $request) {
        // Allow in local/staging OR if user is admin in production
        if (app()->environment(['local', 'staging'])) {
            return true;
        }

        return $request->user()?->isAdmin() ?? false;
    },
];
```

#### Example: Use Laravel Gates

[](#example-use-laravel-gates)

```
// config/user-switcher.php

return [
    // ... other config options

    'authorization_callback' => function (\Illuminate\Http\Request $request) {
        return Gate::allows('switch-users');
    },
];
```

Then define the gate in your `AuthServiceProvider`:

```
use Illuminate\Support\Facades\Gate;

Gate::define('switch-users', function ($user) {
    return $user->hasRole('admin') || $user->hasRole('developer');
});
```

### How Authorization Works During Impersonation

[](#how-authorization-works-during-impersonation)

**Important:** When you're impersonating another user, authorization checks are based on the **original user** (the one who started impersonation), not the currently impersonated user.

This means:

- If an admin (ID: 1) switches to a regular user (ID: 5), the switcher widget remains visible
- The admin can continue switching to other users
- Authorization is always checked against the original admin, not the impersonated user

This prevents the common issue where the switcher disappears after switching to an unauthorized user.

#### Example Scenario

[](#example-scenario)

```
// config/user-switcher.php
'authorization_callback' => function (\Illuminate\Http\Request $request) {
    return $request->user()?->isAdmin() ?? false;
},
```

1. Admin (authorized) logs in → Widget appears ✅
2. Admin switches to Regular User (unauthorized) → Widget **still appears** ✅
3. Admin can switch back or to other users ✅
4. Regular User logs in directly → Widget does **not** appear ✅

### Fallback Behavior

[](#fallback-behavior)

If `authorization_callback` is `null` or not set, the package uses the `enabled` and `environments` config options to determine if user switching is allowed.

Security
--------

[](#security)

The package includes built-in security measures:

- **Session Fixation Protection**: Regenerates session ID after impersonation actions
- **Input Validation**: Validates user identifiers (trims whitespace, rejects empty/overly long values)

**Recommendations:**

- Restrict to non-production environments using the `environments` config
- Implement authorization checks using the `authorization_callback`
- Consider audit logging for compliance (see base package documentation)

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance80

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

131d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d5f42273146f620e730ea92e07d4b8b1949f825c81bdb58d782cba81fe4f2802?d=identicon)[cdoebler](/maintainers/cdoebler)

---

Top Contributors

[![cdoebler](https://avatars.githubusercontent.com/u/798042?v=4)](https://github.com/cdoebler "cdoebler (2 commits)")

---

Tags

impersonationlaravel-packageuser-switcheruser-switching

###  Code Quality

TestsPest

Static AnalysisPHPStan

### Embed Badge

![Health badge](/badges/cdoebler-laravel-user-switcher/health.svg)

```
[![Health](https://phpackages.com/badges/cdoebler-laravel-user-switcher/health.svg)](https://phpackages.com/packages/cdoebler-laravel-user-switcher)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k89.8M1.0k](/packages/spatie-laravel-permission)[php-open-source-saver/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

8359.8M53](/packages/php-open-source-saver-jwt-auth)[laragear/two-factor

On-premises 2FA Authentication for out-of-the-box.

339785.3k8](/packages/laragear-two-factor)[laragear/webauthn

Authenticate users with Passkeys: fingerprints, patterns and biometric data.

403480.4k8](/packages/laragear-webauthn)[casbin/laravel-authz

An authorization library that supports access control models like ACL, RBAC, ABAC in Laravel.

324339.9k4](/packages/casbin-laravel-authz)[alajusticia/laravel-logins

Session management in Laravel apps, user notifications on new access, support for multiple separate remember tokens, IP geolocation, User-Agent parser

2011.0k](/packages/alajusticia-laravel-logins)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
