PHP code example of theupriser / laravel-impersonate

1. Go to this page and download the library: Download theupriser/laravel-impersonate library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

theupriser / laravel-impersonate example snippets


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

Auth::user()->impersonate($other_user);
// You're now logged as the $other_user

Auth::user()->leaveImpersonation();
// You're now logged as your original user.

Route::impersonate();

namespace App\Providers;

class RouteServiceProvider extends ServiceProvider
{
    public function map() {
        Route::middleware('web')->group(function (Router $router) {
            $router->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')

    /**
     * @return bool
     */
    public function canImpersonate()
    {
        // For example
        return $this->is_admin == 1;
    }

    /**
     * @return bool
     */
    public function canBeImpersonated()
    {
        // For example
        return $this->can_be_impersonated == 1;
    }

// With the app helper
app('impersonate')
// Dependency Injection
public function impersonate(ImpersonateManager $manager, $user_id) { /* ... */ }

$manager = app('impersonate');

// Find an user by its ID
$manager->findUserById($id);

// TRUE if your are impersonating an user.
$manager->isImpersonating();

// Impersonate an user. Pass the original user and the user you want to impersonate
$manager->take($from, $to);

// Leave current impersonation
$manager->leave();

// Get the impersonator ID
$manager->getImpersonatorId();

Router::get('/my-credit-card', function() {
    echo "Can't be accessed by an impersonator";
})->middleware('impersonate.protect');

    // The session key used to store the original user id.
    'session_key' => 'impersonated_by',
    // Where to redirect after taking an impersonation.
    // Only used in the built-in controller.
    // You can use: an URI, the keyword back (to redirect back) or a route name
    'take_redirect_to' => '/',
    // Where to redirect after leaving an impersonation.
    // Only used in the built-in controller.
    // You can use: an URI, the keyword back (to redirect back) or a route name
    'leave_redirect_to' => '/'
bash
php artisan vendor:publish --tag=impersonate