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(3mo ago)41.1k↓50%1[1 PRs](https://github.com/verseles/Possession/pulls)MITPHPPHP ^8.2

Since Feb 7Pushed 2mo ago1 watchersCompare

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

READMEChangelogDependencies (2)Versions (15)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

44

—

FairBetter than 92% of packages

Maintenance85

Actively maintained with recent releases

Popularity23

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 63.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

99d 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 (12 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

[lab404/laravel-impersonate

Laravel Impersonate is a plugin that allows to you to authenticate as your users.

2.3k16.4M48](/packages/lab404-laravel-impersonate)[santigarcor/laratrust

This package provides a flexible way to add Role-based Permissions to Laravel

2.3k5.4M43](/packages/santigarcor-laratrust)[overtrue/laravel-follow

User follow unfollow system for Laravel.

1.2k404.7k5](/packages/overtrue-laravel-follow)[codegreencreative/laravel-samlidp

Make your PHP Laravel application an Identification Provider using SAML 2.0. This package allows you to implement your own Identification Provider (idP) using the SAML 2.0 standard to be used with supporting SAML 2.0 Service Providers (SP).

263763.5k1](/packages/codegreencreative-laravel-samlidp)

PHPackages © 2026

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