Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

A Laravel package to impersonate users

A great feature of Laravel Spark is it’s ability to impersonate other users. As an admin you can view all screens as if you are logged in as another user. This allows you to easily spot a problem that your user might be reporting. Laravel-impersonate is a package, made by MarceauKa and Thibault Chazottes that can add this behaviour to any Laravel app.

Here are some code examples taken from the readme.

Auth::user()->impersonate($otherUser); // You're now logged as the $otherUser.

Auth::user()->leaveImpersonation(); // You're now logged as your original user.

$manager = app('impersonate');

// Find an user by its ID

// TRUE if your are impersonating an user.

// Impersonate an user. Pass the original user and the user you want to impersonate
$manager->take($from, $to);

// Leave current impersonation

// Get the impersonator ID

It even includes some handy blade directives:

    <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>

    <a href="{{ route('impersonate.leave') }}">Leave impersonation</a>

Want to know more, take a look at the package on GitHub.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band.
  • Duilio Palacios

    Very nice! I remember working on this feature for a project, but I never thought about making it a package with Blade directive and all 🙂