Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variable exist in laravel's blade directive

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?

like image 527
pupadupa Avatar asked May 25 '16 00:05

pupadupa


People also ask

How do you check if a variable is empty in laravel?

Assumption #1: You Know The Variable Exists Within The View. REMEMBER: an empty array will always return false. Therefore, there is no real need to run it through a function like empty or is null. Comparing it to null will tell you if it exists or not.

What is Blade JavaScript?

A blade encapsulates all the required resources – JavaScript, HTML, CSS, XML, images, etc – to implement a particular high level feature. For example, a blade might implement a map UI, a chat window, a charting module or an alerting mechanism.


1 Answers

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

@isset($var)  @endisset 
like image 59
sanchezcl Avatar answered Oct 15 '22 19:10

sanchezcl