NotDavid
NotDavid

Reputation: 341

Passing conditional disabled attribute to blade component with ternary operator

Is there a way to conditionally pass a disabled attribute to a blade component? For example this question and answer mention how to use the ternary operator to pass in the value of the attribute but the attribute name will be there regardless.

I am specifically trying to use the ternary operator in the blade component tag to add (or not add) the disabled attribute

template code:

<x-button {{!$aircraftType->canIslandBuild($island) ? 'disabled' : ''}}>
    Build
</x-button>

button component code:

<button {{ $attributes->merge(['class' => 'inline-flex']) }}>
    {{ $slot }}
</button>

The error involves adding {{!$aircraftType->canIslandBuild($island) ? 'disabled' : ''}} to the x-button tag.

The error that I'm getting is: syntax error, unexpected token "endif", expecting end of file

Also if I change this {{!$aircraftType->canIslandBuild($island) ? 'disabled' : ''}} to {{''}} the same error happens so I'm curious if you can render strings from php code inside of the component tag header like you can anywhere else in a blade template. I know there are other ways to pass in data and conditionally add the disabled attribute by modifying the button component code but I would like to know if there is an easy solution here.

Upvotes: 4

Views: 4448

Answers (1)

NotDavid
NotDavid

Reputation: 341

Went with matiaslauriti's comment and decided to replace

{{!$aircraftType->canIslandBuild($island) ? 'disabled' : ''}}

with

:disabled="!$aircraftType->canIslandBuild($island)"

without changing anything else. It seems disabled="disabled" is included in the $attributes variable only when the value is true. This means that the button renders a disabled="disabled" only when !$aircraftType->canIslandBuild($island) is true and when it is false, no disabled is rendered on the final html for the button.

Upvotes: 6

Related Questions