Check if variable exist in laravel's blade directive

前端 未结 13 1500
清歌不尽
清歌不尽 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: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.

提交回复
热议问题