Getting Ready For User Impersonation
If your Laravel application has several users and you find yourself doing a lot of blind troubleshooting, you’re going to love this simple user impersonation system!
All you need to have setup to get started is a Laravel application and an admin view that lists all of your users.
Creating The View
Update your admin view that lists your users so that it contains a link for impersonating your users:
Create The Route
Now that we have a link that doesn’t work, let’s fix that by adding our route:
Updating The Controller
Now we can start adding in the logic to start impersonating users by adding the impersonate method to our controller ( You could also go for a RESTful solution, but the concept is the same):
Here we have set a session variable equal to our current user id so that we can re-authenticate as our self when we finish with the impersonated session. We could also clear the session variable and avoid checking to see if it’s equal to 0 or not. But I like to see the logic working if something’s not working right.
At this point, we can click on our link and we will be magically logged in as the user we chose to impersonate.
But how do we get out of impersonation mode?
Ending Impersonated Session
Now all we have to do is update another view:
And just like that we have a link back to our own profile!
You definitely want to add some middeware to protect that route otherwise bad things will happen!
I used something like this for my
admin middleware to get me started:
So far I’ve only made a few refactors, which we will cover in a later post.
Until then, let me know if you have any questions and/or requests!