简体   繁体   中英

Or operator do not work as expected laravel 5.7

It seems very basic but as mentioned in this link or something like this: https://laravel-news.com/blade-or-operator I expect that:

{{ $title or 'login' }}

have to be compiled like this:

if( isset($title) )
{
    echo $title;
}
else {
    echo 'login';
}

or in short way that's equivalent this:

isset($title) ? $title : 'login'

Well, but when I use this, laravel send me an error says:

ErrorException (E_ERROR) Undefined variable: title (View: C:\\xampp\\htdocs\\site\\resources\\views\\layouts\\auth.blade.php) (View: C:\\xampp\\htdocs\\site\\resources\\views\\layouts\\auth.blade.php) Previous exceptions

 Undefined variable: title (View: C:\\xampp\\htdocs\\site\\resources\\views\\layouts\\auth.blade.php) (0) Undefined variable: title (0) 

that means something is wrong with this.

Do you know what could be wrong in my code or configuration?

Thanks in Advance

What the laravel new says:

In the next major release, Laravel 5.7 removes the Blade “or” Operator. Andrew Brown submitted a PR for Laravel 5.7 to Remove Blade Defaults from the framework, due to the new Null Coalesce operator available in PHP 7.

Please look at once. https://laravel-news.com/blade-templates-null-coalesce-operator

You can use.

{{ $title ?? 'login' }}

better to used ??(null coalescing operator) in php 7

{{ $title ?? 'login' }}

It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

The or Operator

The Blade "or" operator has been removed in favor of PHP's built-in ?? "null coalesce" operator, which has the same purpose and functionality:

// Laravel 5.6...
{{ $foo or 'default' }}

// Laravel 5.7...
{{ $foo ?? 'default' }}

You can use like: {{ $title ?? 'login' }} {{ $title ?? 'login' }}

If you are getting such an error, then your $title variable is most likely undefined so double check your code. On a related note, Laravel's blade system doesn't seem to compile that or operator into what you are expecting anymore. Check your cached view file and you would most likely see something like

<?php echo e($title or 'login'); ?>

instead of

<?php echo e(isset($title ) ? $title : 'login'); ?>

which is what you would get with older versions of Laravel, leading to a buggy result (the first one evaluates to a boolean value. The second one returns either the value of $title or the string 'login', just like what you were expecting). That's why it's recommended to use the null coalesce (??) operator now when using Laravel versions 5.7 and up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM