Blade ternary operator without else

17,170

Solution 1

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" : "" }}

Solution 2

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>

Solution 3

You have problem in this line:

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

Here is the solution:

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

Solution 4

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>
Share:
17,170
sarah
Author by

sarah

Updated on June 12, 2022

Comments

  • sarah
    sarah almost 2 years

    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.

  • milo526
    milo526 about 7 years
    The enable here is not necessary (and might even break stuff), this disable is part of the HTML of the button.
  • sarah
    sarah about 7 years
    thanks, I put the whole brackets in quotes so when i put "" after the : , it gave me something very weird but this solved it
  • Giulio Bambini
    Giulio Bambini about 7 years
    I just show you the way.You can do this by using empty string.like this way: {{ ($question->hasATest()) ? disabled : ' ' }}
  • Daniel Azamar
    Daniel Azamar almost 5 years
    This solution worked for me... I was doing something like <input type="text" name="name" value="{{ isset($params) ? $params->name : '' }}" class="form-control">