php
55 lines · 8 steps
How user impersonation works in Laravel
A service that lets an authorized admin log in as another user while remembering how to switch back.
Explained by
highlit
1<?php
2
3namespace App\Services;
4
5use App\Models\User;
6use Illuminate\Support\Facades\Auth;
7use Illuminate\Support\Facades\Session;
8use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
9
10class Impersonation
11{
12 protected const SESSION_KEY = 'impersonator_id';
13
14 public function start(User $target): void
15 {
16 $current = Auth::user();
17
18 if (! $current->can('impersonate', $target)) {
19 throw new AccessDeniedHttpException('You may not impersonate this user.');
20 }
21
22 if ($this->isImpersonating()) {
23 throw new \LogicException('Already impersonating a user.');
24 }
25
26 Session::put(self::SESSION_KEY, $current->getAuthIdentifier());
27
28 Auth::guard('web')->login($target);
29 Session::regenerate();
30 }
31
32 public function stop(): void
33 {
34 if (! $this->isImpersonating()) {
35 return;
36 }
37
38 $original = User::findOrFail(Session::pull(self::SESSION_KEY));
39
40 Auth::guard('web')->login($original);
41 Session::regenerate();
42 }
43
44 public function isImpersonating(): bool
45 {
46 return Session::has(self::SESSION_KEY);
47 }
48
49 public function impersonator(): ?User
50 {
51 return $this->isImpersonating()
52 ? User::find(Session::get(self::SESSION_KEY))
53 : null;
54 }
55}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Stash the original identity in the session before swapping so you always have a route back.
- 2Gate sensitive actions behind an authorization policy check before touching any state.
- 3Regenerating the session on every auth switch prevents session fixation across identities.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-user-impersonation-works-in-laravel-explained-php-bcf1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.