Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blade ternary operator without else

Tags:

php

laravel

blade

I've got a object which has the method hasATest that returns a boolean and depending on the value I want a button to be enabled or disabled so I thought of doing something like this:

<button class="btn btn-xs btn-detail btn-activate" name="question_id" value="{{$question->id}}" id="activate{{$question->id}}"
    "{{ $question->hasATest() ? disabled : }}"> Activate 
</button>

But I don't know what to do about the else. If I remove the :, an error occurs:

"unexpected ="  ... 

Plus it's not like there's the opposite for disabled.

like image 348
sarah Avatar asked Apr 14 '17 20:04

sarah


2 Answers

The ternary operator needs an else as you already discovered, you could try some statements like null or in this case "" to return empty values on the else.

{{ ($question->hasATest()) ? "disabled" : "" }}

like image 185
milo526 Avatar answered Oct 12 '22 06:10

milo526


Just use an empty string for the else part.

<button class="btn btn-xs btn-detail btn-activate" name="question_id" value="{{$question->id}}" id="activate{{$question->id}}"
    {{ $question->hasATest() ? 'disabled' : '' }}> Activate 
</button>

I think you could also use an @if for it instead of a ternary.

<button class="btn btn-xs btn-detail btn-activate" name="question_id" value="{{$question->id}}" id="activate{{$question->id}}"
    @if($question->hasATest()) disabled @endif> Activate
</button>
like image 37
Don't Panic Avatar answered Oct 12 '22 07:10

Don't Panic