PHPackages                             octopyid/laravel-impersonate - 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. [Database &amp; ORM](/categories/database)
4. /
5. octopyid/laravel-impersonate

ActiveLibrary[Database &amp; ORM](/categories/database)

octopyid/laravel-impersonate
============================

Login as a different user quickly

v5.0.0(1mo ago)324130.2k↓29.9%28[1 issues](https://github.com/OctopyID/LaraPersonate/issues)1MITPHPPHP ^8.2CI passing

Since Aug 3Pushed 1mo ago4 watchersCompare

[ Source](https://github.com/OctopyID/LaraPersonate)[ Packagist](https://packagist.org/packages/octopyid/laravel-impersonate)[ GitHub Sponsors](https://github.com/SupianIDz)[ Fund](https://ko-fi.com/SupianIDz)[ RSS](/packages/octopyid-laravel-impersonate/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (10)Dependencies (13)Versions (37)Used By (1)

 [![Demo](demo.gif)](demo.gif)

 [![Tests](https://camo.githubusercontent.com/5791e88f2c9ecbd9e81b23c18bc04ae785871788cbb802ea8a1bc132d64df9a8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f4f63746f707949442f4c617261506572736f6e6174652f74657374732e796d6c3f6272616e63683d6d61696e267374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/5791e88f2c9ecbd9e81b23c18bc04ae785871788cbb802ea8a1bc132d64df9a8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f4f63746f707949442f4c617261506572736f6e6174652f74657374732e796d6c3f6272616e63683d6d61696e267374796c653d666f722d7468652d6261646765) [![Version](https://camo.githubusercontent.com/290cc4baf398b6c874d633045aba56d709bf901d9ad310ae8129f211937ebbae/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f63746f707969642f6c61726176656c2d696d706572736f6e6174652e7376673f7374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/290cc4baf398b6c874d633045aba56d709bf901d9ad310ae8129f211937ebbae/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f63746f707969642f6c61726176656c2d696d706572736f6e6174652e7376673f7374796c653d666f722d7468652d6261646765) [![Downloads](https://camo.githubusercontent.com/7f07985e56f1aa1829258a5b57664b459575cb820df7a5dbd11b88279e6a749f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f63746f707969642f6c61726176656c2d696d706572736f6e6174652e7376673f7374796c653d666f722d7468652d626164676526636f6c6f723d463238443141)](https://camo.githubusercontent.com/7f07985e56f1aa1829258a5b57664b459575cb820df7a5dbd11b88279e6a749f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f63746f707969642f6c61726176656c2d696d706572736f6e6174652e7376673f7374796c653d666f722d7468652d626164676526636f6c6f723d463238443141) [![License](https://camo.githubusercontent.com/dea71c3b7b79e68c6c0012ea6ce0016d1c750404bbd856492466f5ac14f38076/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6f63746f707969642f6c61726176656c2d696d706572736f6e6174652e7376673f7374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/dea71c3b7b79e68c6c0012ea6ce0016d1c750404bbd856492466f5ac14f38076/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6f63746f707969642f6c61726176656c2d696d706572736f6e6174652e7376673f7374796c653d666f722d7468652d6261646765)

Laravel Impersonate
===================

[](#laravel-impersonate)

**LaraPersonate** is a lightweight, zero-dependency impersonation package for Laravel. Easily login as other users to troubleshoot issues or test features, either programmatically or via a beautifully crafted, plug-and-play UI widget.

### ✨ Highlights

[](#-highlights)

- **Zero Dependencies:** No jQuery, Select2, or Webpack. Just 100% Vanilla JS &amp; CSS.
- **Plug &amp; Play UI:** A beautiful, responsive floating widget injected automatically.
- **Secure by Default:** Built-in authorization guards to prevent unauthorized impersonation.
- **Performance Focused:** Database-level search scoping (`scopeImpersonatable`) out of the box.

ImpersonateLaravelImpersonateLaravel[v5.x](https://github.com/OctopyID/LaraPersonate/tree/main)12.x - 13.x[v2.x](https://github.com/OctopyID/LaraPersonate/tree/v2.x)7.x - 8.x[v4.x](https://github.com/OctopyID/LaraPersonate/tree/v4.x)10.x - 11.x[v1.x](https://github.com/OctopyID/LaraPersonate/tree/v1.x)7.x - 8.x[v3.x](https://github.com/OctopyID/LaraPersonate/tree/v3.x)9.x - 10.xInstallation
------------

[](#installation)

> **Warning**
>
> This version is a breaking change, many changes were made to the addition of new features, new UI design, and code structure.
>
> If you are upgrading from an old version, please republish the assets using the `--force` flag, configure and reset the [limitations](#311-defining-limitation) on the User Model according to this version.

To install the package, simply follow the steps below.

### Install The Package

[](#install-the-package)

```
composer require octopyid/laravel-impersonate:^5
```

### Publish The Package

[](#publish-the-package)

```
php artisan vendor:publish --tag="impersonate" --force
```

### Add `HasImpersonation` Trait to User Model

[](#add-hasimpersonation-trait-to--user-model)

Add the trait `Octopy\Impersonate\Concerns\HasImpersonation` to your **User** model.

```
namespace App\Models;

use Octopy\Impersonate\Concerns\HasImpersonation;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasImpersonation;
}
```

If you plan to use the provided UI, you can implement the `Octopy\Impersonate\Contracts\HasImpersonationUI` interface.

By default, the `HasImpersonation` trait already provides a sensible default for the UI configuration. It uses your `name` or `email` as the display text and allows searching via `name` or `email`.

However, you can easily override these defaults to fit your application by adding the methods to your User model:

```
namespace App\Models;

use Octopy\Impersonate\Concerns\HasImpersonation;
use Octopy\Impersonate\Contracts\HasImpersonationUI;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements HasImpersonationUI
{
    use HasImpersonation;

    /**
     * @return string
     */
    public function getImpersonateDisplayText() : string
    {
        // Override the default display text
        return $this->first_name . ' ' . $this->last_name;
    }

    /**
     * This following is useful for performing user searches through the interface,
     * You can use fields in relations freely using dot notation,
     *
     * example: posts.title, department.name.
     */
    public function getImpersonateSearchField() : array
    {
        // Override the default search fields
        return [
            'first_name', 'last_name', 'posts.title',
        ];
    }
}
```

Events
------

[](#events)

There are two events available that can be used to improve your workflow:

- `Octopy\Impersonate\Events\BeginImpersonation` is fired when an impersonation is begin.
- `Octopy\Impersonate\Events\LeaveImpersonation` is fired when an impersonation is leave.

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

[](#configuration)

This configuration is intended to customize the appearance of Laravel Impersonate, if you don't need a UI and only want to use the backend logic, don't forget to set `IMPERSONATE_UI_ENABLED` to `false` in your environment file because it is enabled by default.

Please refer to the [impersonate.php](config/impersonate.php) file to see the available configurations.

ENV KeyDefaultDescription`IMPERSONATE_UI_ENABLED``true`Enable or disable the impersonation UI widget`IMPERSONATE_UI_WIDTH``21rem`Width of the UI widget panel`IMPERSONATE_UI_DEBOUNCE``300`Debounce delay (ms) before triggering the search requestUsage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

By default, you don't need to do anything, but keep in mind, Impersonation can be done by anyone if you don't define the rules of who can do impersonation or who can be impersonated.

#### Defining Limitation &amp; Search Performance

[](#defining-limitation--search-performance)

To limit who can do **impersonation** or who is can be **impersonated**, implement the `canImpersonate()` and `canBeImpersonated()` methods on your User Model to enforce the limitation.

To improve the UI search performance and fix pagination accuracy, you should also utilize the **Database Scope** via `scopeImpersonatable` (or the modern `#[Scope]` attribute in Laravel 11+). This ensures that the search query only loads valid users directly from the database!

The example below uses [Laratrust](https://github.com/santigarcor/laratrust/) for role management where **SUPER\_ADMIN** can perform impersonation against **CUSTOMER**.

```
namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Attributes\Scope; // for Laravel 11+
use Illuminate\Foundation\Auth\User as Authenticatable;
use Octopy\Impersonate\Concerns\HasImpersonation;

class User extends Authenticatable
{
    use HasImpersonation;

    /**
     * DATABASE FILTER (For UI & Search Performance)
     * This limits the users retrieved for the UI dropdown.
     */
    #[Scope]
    public function impersonatable(Builder $query) : void
    {
        $query->whereHasRole('CUSTOMER');
    }

    /**
     * BACKEND AUTHORIZATION (For Core Security)
     * Validates if the authenticated user can impersonate.
     */
    public function canImpersonate() : bool
    {
        return $this->hasRole('SUPER_ADMIN');
    }

    /**
     * BACKEND AUTHORIZATION (For Core Security)
     * Validates if this user can be impersonated by others.
     */
    public function canBeImpersonated() : bool
    {
        return $this->hasRole('CUSTOMER');
    }
}
```

> **Warning**Not defining the limitations in the Model or misdefining them can lead to serious security issues.

### Advanced Usage

[](#advanced-usage)

#### Impersonating User Manually

[](#impersonating-user-manually)

Sometimes you need Impersonating manually, to perform it, you can use the impersonate singleton.

```
impersonate()->begin($admin, $customer);
```

Or you can use the fluent `loginAs()` method which automatically uses the currently authenticated user as the impersonator:

```
impersonate()->loginAs($customer);
```

Or just simply call the impersonation method directly through the User Model.

```
$admin->impersonate($customer);
```

#### Defining Guard

[](#defining-guard)

Sometimes, you want to use custom guards for authentication, instead of the built-in guards.

```
impersonate()->guard('foo')->begin($admin, $customer);
```

#### Leaving Impersonation Mode

[](#leaving-impersonation-mode)

To leave Impersonation mode, you just need to call the `leave` method on impersonate singleton. This will return you to the original user.

```
impersonate()->leave();
```

Or via Model directly

```
$admin->impersonate()->leave();
```

Don't hesitate to use a guard if you need it.

Handling "Session Bleeding" (Security Warning)
----------------------------------------------

[](#handling-session-bleeding-security-warning)

When leaving impersonation (`impersonate()->leave()`), Laravel will regenerate the session ID. However, the existing session data is **not** cleared by default. If the impersonated user adds an item to a shopping cart (or triggers cached data) and the admin leaves the impersonation, the cart data will "bleed" back into the admin's session!

To prevent this, you should listen to the `BeginImpersonation` and `LeaveImpersonation` events and manually clear your application's specific sensitive session keys (e.g., `cart_id`, `checkout_token`).

```
Event::listen(function (LeaveImpersonation $event) {
    session()->forget('cart_id');
});
```

Disclaimer
----------

[](#disclaimer)

This package can pose a serious security issue if used incorrectly, as anybody will be able to take control of any user's account.

By using this package, you agree that Octopy ID and the contributors of this package cannot be held responsible for any damages caused by using this package.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Supian M](https://github.com/SupianIDz)
- [Octopy ID](https://github.com/OctopyID)

License
-------

[](#license)

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

###  Health Score

65

—

FairBetter than 99% of packages

Maintenance90

Actively maintained with recent releases

Popularity52

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity80

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 96% 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

Every ~61 days

Recently: every ~118 days

Total

36

Last Release

47d ago

Major Versions

v1.x-dev → v2.0.02021-04-22

v2.x-dev → v3.0.02022-06-14

v3.0.3 → v4.0.02023-09-23

v3.x-dev → v4.0.22024-04-01

v4.x-dev → v5.0.02026-07-02

PHP version history (7 changes)v1.0.0PHP ^7.0

v1.2.0PHP ^7.1

v1.2.4PHP ^7.1|^7.2|^7.3|^7.4|^8.0

v1.x-devPHP ^7.4|^8.0

v3.0.0PHP ^8.0|^8.1

v4.0.0PHP ^8.1

v5.0.0PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/37969970?v=4)[Supian M](/maintainers/SupianIDz)[@SupianIDz](https://github.com/SupianIDz)

---

Top Contributors

[![SupianIDz](https://avatars.githubusercontent.com/u/37969970?v=4)](https://github.com/SupianIDz "SupianIDz (169 commits)")[![yannisc](https://avatars.githubusercontent.com/u/704389?v=4)](https://github.com/yannisc "yannisc (3 commits)")[![adjarriawan](https://avatars.githubusercontent.com/u/37354675?v=4)](https://github.com/adjarriawan "adjarriawan (1 commits)")[![alaminfirdows](https://avatars.githubusercontent.com/u/30468274?v=4)](https://github.com/alaminfirdows "alaminfirdows (1 commits)")[![Joorren](https://avatars.githubusercontent.com/u/22602428?v=4)](https://github.com/Joorren "Joorren (1 commits)")[![sidewaysglance](https://avatars.githubusercontent.com/u/3285539?v=4)](https://github.com/sidewaysglance "sidewaysglance (1 commits)")

---

Tags

administrationeloquentimpersonatelaravellaravel-packagephpsudo-su

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/octopyid-laravel-impersonate/health.svg)

```
[![Health](https://phpackages.com/badges/octopyid-laravel-impersonate/health.svg)](https://phpackages.com/packages/octopyid-laravel-impersonate)
```

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k55.8M13.1k](/packages/illuminate-database)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.4M354](/packages/psalm-plugin-laravel)[bavix/laravel-wallet

It's easy to work with a virtual wallet.

1.3k1.4M21](/packages/bavix-laravel-wallet)[wnx/laravel-backup-restore

A package to restore database backups made with spatie/laravel-backup.

214456.3k2](/packages/wnx-laravel-backup-restore)[lacodix/laravel-model-filter

A Laravel package to filter, search and sort models with ease while fetching from database.

17562.4k](/packages/lacodix-laravel-model-filter)[api-platform/laravel

API Platform support for Laravel

58190.1k21](/packages/api-platform-laravel)

PHPackages © 2026

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