Check if variable exist in laravel's blade directive

pupadupa picture pupadupa · May 25, 2016 · Viewed 89.6k times · Source

I'm trying to create blade directive which echo variable (if variable defined) or echo "no data" if variable undefined.

This is my code in AppServiceProvider.php:

<?php

namespace App\Providers;

use Blade;
use Illuminate\Support\ServiceProvider;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('p', function($ex) {
            error_log(print_r($ex,true));
            return '<?php $defined_vars = get_defined_vars(); if(array_key_exists(\''. $ex .'\', $defined_vars) ): echo ' . $ex . ' ; else: echo \'no data\'; endif;?>';
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Here is my index.blade.php:

<p class="lead">@p($myvar)</p>

But my directive "p" gives "no data" if variable defined. If I use isset error occurres: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

How could I check inside directives if variable defined?

Answer

sanchezcl picture sanchezcl · Sep 28, 2018

Blade has a directive to check if a variable is set:

@isset($var)

@endisset