colinlongworth's avatar

How to determine if I am impersonating a user?

I have some front-end components that I don't want to load if I am currently impersonating a user e.g. Analytics. Is there a helper function in Laravel Nova 4 which can be used to determine if impersonation is currently active? e.g.

@notImpersonating
<!-- Only include this if we are not impersonating a user -->
<x-analytics />
@endnotImpersonating
0 likes
6 replies
LaryAI's avatar
Level 58

In Laravel Nova 4, you can use the Nova::isImpersonated() method to determine if impersonation is currently active. You can create a custom Blade directive to achieve the desired functionality.

First, open your AppServiceProvider and add the following code to the boot method:

use Laravel\Nova\Nova;

public function boot()
{
    Nova::userImpersonated(function () {
        Blade::directive('notImpersonating', function () {
            return "<?php if (!\Laravel\Nova\Nova::isImpersonated()) { ?>";
        });

        Blade::directive('endnotImpersonating', function () {
            return "<?php } ?>";
        });
    });
}

This code registers two Blade directives: @notImpersonating and @endnotImpersonating. These directives will only be active when impersonation is not active.

Now, you can use these directives in your views like this:

@notImpersonating
    <!-- Only include this if we are not impersonating a user -->
    <x-analytics />
@endnotImpersonating

The x-analytics component will only be included if impersonation is not active.

Remember to run php artisan optimize or php artisan serve to apply the changes.

Note: This solution assumes you are using Laravel Nova 4. If you are using a different version, please refer to the official Laravel Nova documentation for the appropriate method.

martinbean's avatar

@colinlongworth

This reply was automagically generated by our local A.I. Think of it as a one-off attempt to instantly solve your problem. It will not respond to further replies.

colinlongworth's avatar

@martinbean I know, I wasn't sure if learns or otherwise from feedback, hence my comment of an non-existing function.

neilgilmour's avatar

Incase you're still working on this, there are a couple of ways I've been checking this.

The Nova docs on impersonation have this snippet;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Laravel\Nova\Contracts\ImpersonatesUsers;

Route::get('/impersonation', function (Request $request, ImpersonatesUsers $impersonator) {
    if ($impersonator->impersonating($request)) {
        $impersonator->stopImpersonating($request, Auth::guard(), User::class);
    }
});

The $impersonator->impersonation($request) eventually checks for a session key 'nova_impersonated_by', so I've been using $request->session()->has('nova_impersonated_by'). This key stores the impersonating user's id.

Please or to participate in this conversation.