Check if variable exist in laravel's blade directive

前端 未结 13 1429
清歌不尽
清歌不尽 2021-02-03 19:23

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

相关标签:
13条回答
  • 2021-02-03 19:28

    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') }}">
    
    0 讨论(0)
  • 2021-02-03 19:28

    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; ?>";
        
    });
    
    0 讨论(0)
  • 2021-02-03 19:29

    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')
    
    0 讨论(0)
  • 2021-02-03 19:31

    You can use in Blade functionality for checking isset i.e

    {{ $checkvariable or 'not-exist' }}
    

    https://laravel.com/docs/5.2/blade#displaying-data

    0 讨论(0)
  • 2021-02-03 19:36

    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

    0 讨论(0)
  • 2021-02-03 19:36

    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.

    0 讨论(0)
提交回复
热议问题