Show Laravel Debugbar Only to Specific Users

Published on September 21, 2021 46 sec read

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. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.

Follow