Laravel

How to implement Laravel impersonate

How to implement Laravel impersonate

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.

 

Here is a full documentation of laravel impersonate: https://github.com/404labfr/laravel-impersonate

 

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
				
			

Add the service provider at the end of your config/app.php:

				
					 'providers' => [
     // ...
     Lab404\Impersonate\ImpersonateServiceProvider::class,
  ],
				
			

Add the trait Lab404\Impersonate\Models\Impersonate to your User model.

Using the built-in controller

In your routes file, under web middleware, you must call the impersonate route macro.

				
					 Route::impersonate();

 // Where $id is the ID of the user you want impersonate
 route('impersonate', $id)

 // Or in case of multi guards, you should also add `guardName` (defaults to `web`)
 route('impersonate', ['id' => $id, 'guardName' => 'admin'])

 // Generate an URL to leave current impersonation
 route('impersonate.leave')
				
			

Blade

There are three Blade directives available.

When the user can impersonate

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

When the user can be impersonated

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

When the user is impersonated

				
					 @impersonating($guard = null)
     <a href="{{ route('impersonate.leave') }}">Leave impersonation</a>
 @endImpersonating
				
			

That’s it. Enjoy.

Share On: