Show Laravel Debugbar Only to Specific Users

Hello artisans! In this article, I’m going to share how to show Laravel Debugbar only to specific users. Let’s see:

Table of Contents

  1. Create a Middleware
  2. Show via User ID
  3. Show via User IP

Create a Middleware

Run this command to create a middleware named DebugBarMiddleware:

php artisan make:middleware DebugBarMiddleware

Then register the middleware to Kernel.php in $middleware array:

Kernel.php
// register globally
protected $middleware = [
  //
  \App\Http\Middleware\DebugBarMiddleware::class,
];

// or register in a speceific route group
protected $middlewareGroups = [
  'web' => [
    //
    \App\Http\Middleware\DebugBarMiddleware::class,
  ],
];

Show via User ID

Open the DebugBarMiddleware from app\Http\Middleware location and set user ids like:

DebugBarMiddleware.php
/**
 * Handle an incoming request.
 *
 * @param \Illuminate\Http\Request $request
 * @param \Closure $next
 * @return mixed
 */
public function handle(Request $request, Closure $next)
{
  if (auth()->user() && in_array(auth()->id(), [1,5,10])) {
    \Debugbar::enable();
  } else {
    \Debugbar::disable();
  }

  return $next($request);
}

Show via User IP

We can also specify user IPs. Open the middleware and set user IPs to $allowd_ips array.

DebugBarMiddleware.php
/**
 * Handle an incoming request.
 *
 * @param \Illuminate\Http\Request $request
 * @param \Closure $next
 * @return mixed
 */
public function handle(Request $request, Closure $next)
{
  $allowd_ips = ['192.168.2.3', '192.168.4.50', '192.168.21.35'];

  if(in_array(request()->ip(), $allowd_ips)) {
    \Debugbar::enable();
  } else {
    \Debugbar::disable();
  }

  return $next($request);
}

That’s all. Thanks for reading.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.