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 namespace App\Listeners;
How event subscribers group listeners in Laravel
event-driven
subscribers
queues
Intermediate
6 steps
python
import secrets from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import APIKeyHeader
API key authentication as a FastAPI dependency
authentication
dependency-injection
api-keys
Intermediate
8 steps
php
class OrderReceiptController extends Controller { public function store(Request $request, Order $order) {
Handling receipt uploads in a Laravel controller
file-upload
validation
authorization
Intermediate
5 steps
javascript
import { useReducer, useCallback } from 'react'; function historyReducer(state, action) { const { past, present, future } = state;
Undo/redo form state with a React reducer
undo-redo
reducer
immutability
Intermediate
10 steps
php
<?php final class RememberMeCookie {
Signed remember-me cookies in PHP
authentication
hmac
cookies
Intermediate
8 steps
php
<?php namespace App\Http\Middleware;
Caching HTTP responses with Laravel middleware
middleware
caching
http
Intermediate
8 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.