Allow Access to Specific Routes if Debug Mode is Enabled in Laravel 9

Allow Access to Specific Routes if Debug Mode is Enabled in Laravel 9

In some applications can be required to define routes which can be accessed only if debug mode is enabled. These routes can be used for testing or development purpose.

This tutorial shows example how to allow access to specific routes if debug mode is enabled in Laravel 9 application.

The APP_DEBUG environment variable specifies if debug mode is enabled. It can be changed in .env file:

.env

APP_DEBUG=true

Don't forget to clear configuration cache after changes:

php artisan config:cache

Create middleware to check if debug mode is enabled. If disabled, throw AccessDeniedHttpException exception.

app/Http/Middleware/AllowIfDebugModeEnabled.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class AllowIfDebugModeEnabled
{
    public function handle(Request $request, Closure $next): mixed
    {
        if (config('app.debug')) {
            return $next($request);
        }

        throw new AccessDeniedHttpException('Access Denied');
    }
}

Define the middleware in the routeMiddleware array which can be found in the Kernel.php file.

app/Http/Kernel.php

<?php

namespace App\Http;

use App\Http\Middleware\AllowIfDebugModeEnabled;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    // ...

    protected $routeMiddleware = [
        // ...
        'debug' => AllowIfDebugModeEnabled::class,
    ];
}

Assign middleware to specific routes, which can be accessed only if debug mode is enabled.

routes/web.php

<?php

use App\Http\Controllers\TestController;
use Illuminate\Support\Facades\Route;

Route::middleware('debug')->group(function () {
    Route::get('/test', [TestController::class, 'index']);
});

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;

class TestController extends Controller
{
    public function index(): Response
    {
        return new Response();
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.