DEV Community

Cover image for How to use User Impersonate in Laravel 9
Snehal Rajeev Moon
Snehal Rajeev Moon

Posted on

How to use User Impersonate in Laravel 9

Hello Reader,

In today's blog I am going to show you how we can implement user impersonate in our project.

What is user impersonate and why we use it in projects?

  • User Impersonate is useful when we want to login on behalf of admin user.

  • When we are a super-admin and we want to know about our users what they do in their account then this package is useful to check their activity.

  • If you implemented impersonate in your project then you need to maintain it because it may cause a security issue as well as user's privacy issue.

Steps to follow

  1. Install user impersonate package
  2. Setup User Model
  3. Define routes
  4. Create controller and Implement Impersonate logic

Step 1:
So let's start with installing impersonate on your project copy the below code where we will install this package using composer.

composer require lab404/laravel-impersonate
Enter fullscreen mode Exit fullscreen mode

Step 2:
After installation we need to setup user model. Open User.php model and add use Impersonate and use Lab404\Impersonate\Models\Impersonate; to it as shown below.

Image description

Step 3:
Defining route: You can define a built in route as below

Route::impersonate();
Enter fullscreen mode Exit fullscreen mode

or, Alternately define route as,

route('impersonate', $id)
Enter fullscreen mode Exit fullscreen mode

where $id is the user ID whom we want to impersonate. For example,

Route::get({user}/impersonate, [ControllerName::class, 'method_name')->name('user.impersonate);
Enter fullscreen mode Exit fullscreen mode

and to leave impersonate the route will be define as

route('impersonate.leave');

Route::get('/leave-impersonate', [ControllerName::class,'method_name'])->name('user.leave-impersonate');
Enter fullscreen mode Exit fullscreen mode

Step 4:
Now create a controller where you want to implement impersonate logic and add below code in it.

// to create controller
php artisan make:controller ControllerName

// method used to make user impersonate
public function method_name(User $user) 
{
    auth()->user()->impersonate($user);

    return redirect()->back();
}

// method used to leave impersonate user
public function method_name() 
{
    auth()->user()->leaveImpersonation();

    return redirect()->back();
}
Enter fullscreen mode Exit fullscreen mode

In this way we can implement user impersonate in our project.
If you want to know more about it you can visit on below github
(https://github.com/404labfr/laravel-impersonate)

Thanks for Reading!
❀️ πŸ¦„

Top comments (1)

Collapse
 
pankajsondagar07 profile image
Pankaj Sondagar

It is not working for passport API, can you please give an example How to implement it in API?