PHP code example of octopyid / laravel-impersonate

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

    

octopyid / laravel-impersonate example snippets


namespace App\Models;

use Octopy\Impersonate\Concerns\HasImpersonation;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasImpersonation;
    
    /**
     * @return string
     */
    public function getImpersonateDisplayText() : string
    {
        return $this->name;
    }
    
    /**
     * This following is useful for performing user searches through the interface,
     * You can use fields in relations freely using dot notation,
     * 
     * example: posts.title, department.name.   
     */
    public function getImpersonateSearchField() : array
    {
        return [
            'name', 'posts.title',
        ];
    }
}


use Octopy\Impersonate\Concerns\HasImpersonation;
use Octopy\Impersonate\Authorization;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasImpersonation;
    
    /**
     * @param  Authorization $authorization
     * @return void
     */
    public function setImpersonateAuthorization(Authorization $authorization) : void
    {
        $authorization->impersonator(function (User $user) {
            return $user->hasRole('SUPER_ADMIN');
        });

        $authorization->impersonated(function (User $user) {
            return $user->hasRole('CUSTOMER');
        });
    }
}

impersonate()->begin($admin, $customer);

$admin->impersonate($customer);

impersonate()->guard('foo')->begin($admin, $customer);

impersonate()->leave();

$admin->impersonate()->leave();