0

I have some variables in my blade files, These variables may be empty so I use or when I trying to echo the variable .

like this:

<div style="background-color: {{ $color or '#888' }}">

but when I run my application I got this error:

ErrorException (E_ERROR)
Undefined variable: color

I searched in internet and found for checking the variables I should use or but I don't know why I got error !!

P.S: This code run on my previous server without any problem, but in new server I have this error ! previous server was Apache+PHP 7.2 and the new server is Nginx+PHP-FPM .

MajAfy
  • 3,007
  • 10
  • 47
  • 83

1 Answers1

1

The variable has to exist at least in order for that check to work. You can try this:

{{ isset($color) ?: '#888' }}
nakov
  • 13,938
  • 12
  • 60
  • 110
  • Thank you, but as I said this code worked on my previous server, I think I need some change in php configuration – MajAfy Oct 28 '18 at 14:13
  • I tried your code on my local machine, I have PHP 7.1.19 and it doesn't work, it throws the same error. – nakov Oct 28 '18 at 14:14
  • Reading further here: http://php.net/manual/en/language.operators.logical.php ?? will work without a isset check, but the or is equal to || check which checks just for boolean values, not if something exists or not. So I doubt that your code worked if the variable wasn't passed to the view at all. – nakov Oct 28 '18 at 14:17
  • But according to this document : https://laravel.com/docs/5.2/blade#displaying-data we can use `or` for checking the variable – MajAfy Oct 28 '18 at 14:44
  • 1
    This may be due to PHP version requirements. In older versions such comparison is possible, while in later it may not be. Besides, the documentation may not have it right - this is best tested in the current version of PHP. – Daniel Protopopov Oct 28 '18 at 14:56
  • 1
    Yeah, and that depends which version of laravel you use. Because the blade `or` logical operator got removed: https://laravel.com/docs/5.7/upgrade – nakov Oct 28 '18 at 15:01