2

I'm using the following code in my form currently:

{{ $errors->has('email') ? ' has-error' : '' }}

I tried changing it to this:

{{ $errors->has('email') ?: ' has-error' }}

But now the class is added even if it has no errors. Why is this happening? Just curious.

kjdion84
  • 9,552
  • 8
  • 60
  • 87

2 Answers2

1

That's how null coalesce operator works. For example, this will return 5:

false ?: 5

When you use has() method which will return true or false, null coalesce operator will always return 'has-error'.

So, just use the ternary operator.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
1

it seems null coalescing works bit differently then ternary even if the variable is empty ( '' ) i.e false the null coalescing will treat the variable as true but the shorthand ternary operator won't. And that's something to have in mind.

https://3v4l.org/fnG9W

for more info on null coalescing vs ternary.

PHP ternary operator vs null coalescing operator

Riaz Laskar
  • 1,317
  • 9
  • 17