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.ph
You can do it in few different ways.
Sample-1:
@if( !empty($data['var']))
{{ $data['var'] }}
@endif
Sample-2:
{{ $data['var'] or 'no data found' }}
Sample-3: Using ternary operator
<a href="" class="{{ ( ! empty($data['var'] ? $data['var'] : 'no data found') }}">
To check if variable exist in Laravel blade directive, do this:
Blade::directive('datetime', function ($value) {
return "<?php echo isset($value) ? ($value)->format('d/m/Y H:i:s') : null; ?>";
});
What are you trying to pass to your custom directive? If it's just a string/int the following should work.
Blade::directive('p', function($expression){
$output = $expression ? $expression : 'nodata';
return "<?php echo {$output}; ?>";
});
In Blade Template
@p('Foo')
You can use in Blade functionality for checking isset i.e
{{ $checkvariable or 'not-exist' }}
https://laravel.com/docs/5.2/blade#displaying-data
Try checking if the variable is empty:
@if(empty($myvar))
<p>Data does not exist</p>
@else
<p>Your data is here!</p>
@endif
Can also check this thread
You can use the @isset
blade directive to check whether the variable is set or not. Alternatively, if you have the default value for that variable you can directly use it as {{ $vatiable ?? 'default_value' }}
. The ??
way is available in Laravel v5.7 onwards.
If you want to check for multiple variables at once, you can do it by applying AND operation to expression as @if(isset($var_one) && isset($var_two))
.
There are also other ways (lengthy) using @if
directive as @if(isset($variable))
but it's not recommended.
Some developer uses @
symbol for error control in a similar situation. The at-sign (@) is used as error control operator in PHP. When an expression is prepended with the @ sign, error messages that might be generated by that expression will be ignored. If the track_errors
feature is enabled, an error message generated by the expression and it will be saved in the variable $php_errormsg
. This variable will be overwritten on each error. The use of @ is very bad programming practice as it does not make the error disappear, it just hides them, and it makes debugging a lot worse since we can’t see what’s actually wrong with our code.