Home » Php » php – Blade ternary operator without else

php – Blade ternary operator without else

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&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" : "" }}

Answer:

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>

Answer:

You have problem in this line:

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

Here is the solution:

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

Answer:

For those who has to check over the Non-boolean variable is there or not

e.g. $question->test returns test name (string) then you can use isset

<td> 
{{ isset($question->test) ? $question->test : __('question.no_test') }}
</td>