Search code examples
phplaravellaravel-blade

Laravel default blade behaviour


In the blade views, if I echo an unset variable I get an error. So the usual answer to this problem is:

{{ isset($variable) ? $variable : '' }}

I was wondering if there was a way to make it the default behaviour for blade templates, where an unset variable would just display empty string.


Solution

  • You can use simply:

    {{ $variable ?? '' }}
    

    But if you want to make this behavior default for all variables without explicitly using the ?? operator you should code blade compiler.

    1. Extend the Blade Compiler:
    namespace App\Extensions;
    
    use Illuminate\View\Compilers\BladeCompiler;
    
    class CustomBladeCompiler extends BladeCompiler
    {
        protected function compileEchoDefaults($value)
        {
            return preg_replace('/\{\{\s*(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}\}/', '{{ $1 ?? \'\' }}', $value);
        }
    
        public function compileString($value)
        {
            $value = $this->compileEchoDefaults($value);
            return parent::compileString($value);
        }
    }
    
    1. AppServiceProvider:
    use App\Extensions\CustomBladeCompiler;
    
    public function register()
    {
        $this->app->singleton('blade.compiler', function () {
            return new CustomBladeCompiler($this->app['files'], $this->app['config']['view.compiled']);
        });
    }