PHP code example of ukeloop / laravel-impersonatable-guard

1. Go to this page and download the library: Download ukeloop/laravel-impersonatable-guard 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/ */

    

ukeloop / laravel-impersonatable-guard example snippets


// config/auth.php

'guards' => [
    'web' => [
        'driver' => 'impersonatable.session',
        'provider' => 'users',
    ],
],

Auth::guard('web')->impersonate($user);

Auth::guard('web')->onceImpersonate($user);

Auth::guard('web')->exitImpersonation();

$originalUser = Auth::guard('web')->originalUser();

$isImpersonated = Auth::guard('web')->impersonated();

Route::get('/protect-form-impersonation', 'ExampleController@handleImportantRequest')->middleware('impersonation.protect');

Route::get('/protect-form-impersonation', 'ExampleController@handleImportantRequest')->middleware('impersonation.protect:specified-guard');

use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use RuntimeException;
use Ukeloop\ImpersonatableGuard\Contracts\ImpersonatableGuard;

class ImpersonationController extends Controller
{
    /**
     * Start impersonating the specified user.
     */
    public function impersonate(User $user): RedirectResponse 
    {
        $guard = Auth::guard('web');

        if (!$guard instanceof ImpersonatableGuard) {
            throw new RuntimeException('This guard is not allowed to impersonate.');
        }

        $guard->impersonate($user);

        return redirect('/');
    }

    /**
     * Stop impersonating the current user and return to the original user context.
     */
    public function exit(): RedirectResponse 
    {
        $guard = Auth::guard('web');

        if (!$guard instanceof ImpersonatableGuard) {
            throw new RuntimeException('This guard is not allowed to impersonate.');
        }

        $guard->exitImpersonation();

        return redirect('/');
    }
}

use Ukeloop\ImpersonatableGuard\Contracts\ImpersonatableGuard;

class CustomImpersonateGuard implements ImpersonatableGuard 
{
    // Define your own logic
}