Inquisitive's avatar

Best way to enable laravel debugbar on for superadmin or for certain ip

For now, I have created a middleware and added it into the 'web' group in kernel. MY DebugBarMiddleware have:

    {
        $debugBarEnabledIps = DebugBarWhitelistedIpAddress::where('updated_at','>=', Carbon::now()->subDays(7))
        ->pluck('ip_address')->toArray();

        if (auth()->check() && in_array($request->ip(), $debugBarEnabledIps)) {
            app('debugbar')->enable();
            config('app.debug', true);
        }else{
            config('app.debug', false);
            app('debugbar')->disable();
        }
        return $next($request);
    }

The above code works fine only, when I set APP_DEBUG to true on env. And, with that, any of the other errors are also becoming visible. With APP_DEBUG = false, it used to show only 500 server error.

Is there any better approach to deal with it?

0 likes
6 replies
Inquisitive's avatar

@SilenceBringer I am using an older version of laravel debug bar 3.6, it's a laravel 6 project. But still. I can see the enabled field in the config, so I tried this instead.

$debugBarEnabledIps = DebugBarWhitelistedIpAddress::where('updated_at','>=', Carbon::now()->subDays(7))
->pluck('ip_address')->map(function($item){
        return Crypt::decrypt($item);
    })->toArray();

if (auth()->check() && in_array($request->ip(), $debugBarEnabledIps)) {
    Config::set('debugbar.enabled', true);
}

return $next($request);

But, its working only when DEBUGBAR_ENABLED is set to true on env, else not working.

thinkverse's avatar

Also, it's recommended only to use Laravel Debugbar in development, and rely instead on error trackers, like Flare, Bugsnag or Senty.

It's better to track errors that way and set up loggers for other things like slow queries and such.

1 like
phuongdm's avatar

I tried add new middleware in kernel http file, let try and good luck :)

protected $middlewareGroups = [
        'web' => [
            ...,
            EnableDebugBarMiddleware::class,
        ],

make new middleware EnableDebugBarMiddleware class extends from Barryvdh\Debugbar\Middleware\InjectDebugbar

class EnableDebugBarMiddleware extends InjectDebugbar
{
   ...
    public function handle($request, Closure $next)
    {
        if (auth()->user()?->isSuperAdmin()) {
            config()->set('debugbar.enabled', true);
            app()->register(\Barryvdh\Debugbar\ServiceProvider::class);
        }

        return parent::handle($request, $next);
    }
}
kyobul's avatar

In order to work you have to do it in reverse : in .env file

APP_DEBUG=true		

then in your middleware you set

Debugbar:disable() 	 

for any account that is NOT superadmin or whatever you want. And it will work. Id app_debug is set to false it will never work.

martinbean's avatar

Yeah, any one reading this, do not enabled APP_DEBUG=true is a non-local environment.

1 like

Please or to participate in this conversation.