Mike Cobb
Mike Cobb

Reputation: 3

@foreach loop in Laravel blade causes x-text reference problem

The following code is in a @foreach loop in a form in a Laravel blade:

<div class="col-span-2 place-self-end flex items-center">
    <div class="form-switch">
        <input type="checkbox" id="change_inverter.{{ $loop->index}}"
            wire:model="toDos.{{ $loop->index}}.change_inverter" class="sr-only" />
        <label class="bg-slate-400 dark:bg-slate-700" for="change_inverter.{{ $loop->index}}">
            <span class="bg-white shadow-sm" aria-hidden="true"></span>
        </label>
    </div>
    <div class="font-semibold text-slate-800 dark:text-slate-100 italic mx-4"
    x-text="$wire.toDos.{{ $loop->index}}.change_inverter ? 'Yes' : 'No'">
    </div>
</div>
<div>
    @error('toDos.{{ $loop->index}}.change_inverter') <span
        class="text-sm font-normal text-rose-500 dark:text-rose-200">{{ $message }}</span>
    @enderror
</div>

The form works fine but the x-text doesn’t update and throws an Alpine Expression Error: Unexpected number.

If I change the x-text code to:

x-text="$wire.toDos[{{ $loop->index}}]['change_generator'] ? 'Yes' : 'No'"

the x-text updates without errors but if the form is updated it throws the error Cannot read properties of undefined (reading 'change_generator')

So far I’ve failed to come up with a work around to set the x-text property so no errors are thrown. Any thoughts welcome.

Upvotes: 0

Views: 25

Answers (1)

TUPKAP
TUPKAP

Reputation: 5309

The x-text attibute value is javascript, so the second syntax you proposed should work, and I can't reproduce your error.
I suppose that in some circumstances an element addressed by $loop->index does not contain the key change_generator

Another option is to use the dot notation and the optional chaining syntax, since non numeric PHP associative array keys are converted to properties on the JS side:

<div x-text="$wire.toDos[{{ $loop->index}}]?.change_generator ? 'Yes' : 'No'">
</div>

Upvotes: 0

Related Questions