EmJeiEn
EmJeiEn

Reputation: 1443

Laravel 6 - Conditionally enable debug page on production mode

I used to run debug true in production when needed with Laravel 5 the following way:

'debug' => env('APP_DEBUG', $_SERVER['REMOTE_ADDR'] == 'myipaddress' ? true : false),

However Laravel 6 doesn't let me use it, when I do artisan config:cache, artisan complains that:

variable $_server['REMOTE_ADDR'] is not defined and exists.

Is there another way someone has found out to be working to do this with Laravel 6?

Upvotes: 0

Views: 2306

Answers (2)

Simon Benjámin
Simon Benjámin

Reputation: 71

I made a composer package that can turn on APP_DEBUG based on COOKIE and IP: https://github.com/Benjaminhu/laravel-app-debug-dynamic

Usage (Dynamic enable APP_DEBUG via COOKIE & IP):

composer require benjaminhu/laravel-app-debug-dynamic

Setup .env (remember: in production mode alway set: APP_DEBUG=false!):

APP_DEBUG=false
APP_DEBUG_DYNAMIC_COOKIE_NAME=<CHOOSE COOKIE NAME>
APP_DEBUG_DYNAMIC_COOKIE_SECRET=<CHOOSE COOKIE SECRET>

If the data matches, the debug is activated dynamically!

Upvotes: 0

Hafez Divandari
Hafez Divandari

Reputation: 9029

You can't cache dynamic configs. there is no request and no $_server when Laravel tries to cache your configs.

You must disable your debug on production (APP_DEBUG = false) and check the log for any errors.

But if you insist to enable app debug dynamically, you can use middleware:

  1. Create a new middleware using Artisan command:

    php artisan make:middleware EnableDebug
    
  2. This command will place a new EnableDebug class within your app/Http/Middleware directory. Modify it like this:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class EnableDebug
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            config(['app.debug' => $request->ip() === 'myipaddress']);
    
            return $next($request);
        }
    }
    
  3. List your middleware class at the end of the $middleware property of your app/Http/Kernel.php class:

    protected $middleware = [
        //...
        \App\Http\Middleware\EnableDebug::class,
    ];
    

Upvotes: 6

Related Questions