PHPackages                             verseles/possession - 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. verseles/possession

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

verseles/possession
===================

Laravel user impersonation package with Sanctum compatibility

0.0.11(4mo ago)41.2k↓85.7%1[4 PRs](https://github.com/verseles/Possession/pulls)MITPHPPHP ^8.2

Since Feb 7Pushed 2d ago1 watchersCompare

[ Source](https://github.com/verseles/Possession)[ Packagist](https://packagist.org/packages/verseles/possession)[ RSS](/packages/verseles-possession/feed)WikiDiscussions main Synced yesterday

READMEChangelogDependencies (2)Versions (22)Used By (0)

Laravel Possession - User Impersonation Package
===============================================

[](#laravel-possession---user-impersonation-package)

[![Latest Version](https://camo.githubusercontent.com/5ea18f5f2fb3c177c258d6314dc5bab9c60b7b8b86136e99f2c25480d190df5c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f76657273656c65732f706f7373657373696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/verseles/possession)

A simple user impersonation package for Laravel with Sanctum compatibility.

Features
--------

[](#features)

- Secure user impersonation system
- Global `possess()` and `unpossess()` methods
- Comprehensive exception handling
- Session-based impersonation
- Sanctum compatibility
- Simple administration controls
- Visual impersonation indicator
- Easy to integrate

> It wasn't tested with all Laravel versions, only with Laravel 11 and 12.

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

[](#installation)

1. Install via Composer:

```
composer require verseles/possession
```

2. Publish the configuration file (optional):

```
php artisan vendor:publish --tag=possession-config
```

3. Add the trait to your User model:

```
use Verseles\Possession\Traits\ImpersonatesUsers;

class User extends Authenticatable
{
    use ImpersonatesUsers;

    // Add your possession logic
    public function canPossess()
    {
        return $this->is_admin; // Your admin check logic
    }

    public function canBePossessed()
    {
        return !$this->is_admin; // Example restriction
    }
}
```

Usage
-----

[](#usage)

### Global Methods

[](#global-methods)

Use the facade for direct impersonation control:

```
use Verseles\Possession\Facades\Possession;

// Possess a user (accepts ID, email, or User model instance)
try {
    Possession::possess($targetUser);
} catch (\Verseles\Possession\Exceptions\ImpersonationException $e) {
    // Handle exception
    return redirect()->back()->withErrors(['impersonation' => $e->getMessage()]);
}

// Stop possessing
try {
    Possession::unpossess();
} catch (\Verseles\Possession\Exceptions\ImpersonationException $e) {
    // Handle exception
    return redirect()->back()->withErrors(['impersonation' => $e->getMessage()]);
}
```

### Web Routes Example

[](#web-routes-example)

```
// routes/web.php
use Verseles\Possession\Facades\Possession;

Route::middleware(['web', 'auth:'.config('possession.admin_guard')])->group(function () {
    Route::post('/possession/impersonate/{user}', function ($user) {
        try {
            Possession::possess($user);
            return redirect()->route('dashboard');
        } catch (\Verseles\Possession\Exceptions\ImpersonationException $e) {
            return back()->withErrors(['impersonation' => $e->getMessage()]);
        }
    });

    Route::post('/possession/leave', function () {
        try {
            Possession::unpossess();
            return redirect()->route('admin.dashboard');
        } catch (\Verseles\Possession\Exceptions\ImpersonationException $e) {
            return back()->withErrors(['impersonation' => $e->getMessage()]);
        }
    });
});
```

### Blade Templates

[](#blade-templates)

**Start Impersonation:**

```
@if(auth()->check() && auth()->user()->canImpersonate())

    @csrf
    Impersonate User

@endif
```

**Stop Impersonation:**

```
@include('possession::impersonating')
```

Error Handling
--------------

[](#error-handling)

The package throws specific exceptions you can catch:

```
use Verseles\Possession\Exceptions\ImpersonationException;

try {
    Possession::possess($user);
} catch (ImpersonationException $e) {
    // Handle specific error types:
    if ($e->getCode() === 403) {
        // Authorization error
    }

    // General error handling
    return back()->withErrors(['impersonation' => $e->getMessage()]);
}
```

Available exceptions:

- `UnauthorizedPossessException`
- `UnauthorizedUnpossessException`
- `TargetCannotBePossessedException`
- `SelfPossessionException`
- `NoImpersonationActiveException`
- `AlreadyImpersonatingException`
- `AdminNotFoundException` — original admin not found during unpossess (e.g., deleted)

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

[](#configuration)

Edit `config/possession.php` after publishing:

```
return [
    'user_model' => App\Models\User::class,
    'admin_guard' => 'web',
    'session_keys' => [
        'original_user' => 'possession.original_user_id',
    ],
];
```

Security Considerations
-----------------------

[](#security-considerations)

- Always protect impersonation routes with middleware
- Use separate guards for admin and regular users
- Regularly review your `canPossess()` and `canBePossessed()` logic
- Never expose impersonation controls to non-administrative users

License
-------

[](#license)

The MIT License (MIT)

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance88

Actively maintained with recent releases

Popularity22

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 68.2% 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 ~36 days

Recently: every ~87 days

Total

11

Last Release

144d ago

PHP version history (3 changes)0.0.2PHP ^8.0

0.0.9PHP ^8.1

0.0.10PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/934b53b68624e78343e3f3367897cbaf5fb01475511a1650d2c99c972c810ec6?d=identicon)[insign](/maintainers/insign)

---

Top Contributors

[![insign](https://avatars.githubusercontent.com/u/1113045?v=4)](https://github.com/insign "insign (15 commits)")[![addamdav](https://avatars.githubusercontent.com/u/114454536?v=4)](https://github.com/addamdav "addamdav (7 commits)")

### Embed Badge

![Health badge](/badges/verseles-possession/health.svg)

```
[![Health](https://phpackages.com/badges/verseles-possession/health.svg)](https://phpackages.com/packages/verseles-possession)
```

###  Alternatives

[statamic-rad-pack/runway

Eloquently manage your database models in Statamic.

135224.7k7](/packages/statamic-rad-pack-runway)[jeremy379/laravel-openid-connect

OpenID Connect support to the PHP League's OAuth2 Server. Compatible with Laravel Passport.

59437.0k9](/packages/jeremy379-laravel-openid-connect)[ecotone/laravel

Ecotone for Laravel — CQRS, Event Sourcing, Sagas, Durable Workflows, and Outbox on top of Laravel Queue, via PHP attributes.

21318.6k3](/packages/ecotone-laravel)

PHPackages © 2026

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