1

laravel blade ternary operator

 {{ isset($name) ? $name : 'Default' }}

we can write short form

{{ $name or 'Default' }}

but it returns the Boolean value when implement like:

 {{$videos->count() or 'no video' }} //if count return 1 always, 

but this code

  {{ $videos->count()}} // return 4

how to implement this by short form in blade ternary operator

Cœur
  • 37,241
  • 25
  • 195
  • 267
Al-Amin
  • 748
  • 2
  • 13
  • 28

2 Answers2

1

You want to show the count if it's > 0. Else you want to show the text.

Your count() is always not null (0 or higher). So what you want to do is this:

{{$videos->count() > 0 ? $vides->count() : 'no video'}}

schellingerht
  • 5,726
  • 2
  • 28
  • 56
0

Seen as you are using PHP 7.1 you can use the new Null Coalescing Operator. All PHP 7's new features can be found in the docs: http://php.net/manual/en/migration70.new-features.php

Your code would then look like this:

{{$videos->count() ?? 'no video' }}

There is a detailed description of the operator in the docs:

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

Josh Bolton
  • 688
  • 6
  • 19