Search code examples
laravellaravel-livewirealpine.js

Foreach loops in Alpine.js from select dropdown


I have a select option loop and wanted to try alpinejs. If a user selects a certain option, a certain DIV will show up.

Here's my select

<div class="mt-4"> 
<select required wire:model.defer="task_id" />
   <option value=""> Select a Task </option>
            @foreach($tasktypes as $task)
            <option value="{{$task->id}}"> {{$task->name}}</option>
            @endforeach                     
</select>
</div>

so if task->id == 1

a new <div> id 1 should appear here </div> should appear below.

I tried below to no luck. I'm just starting TALL Stack

<div class="mt-4" x-data="$wire.tasktypes->id : false"> 
<select required wire:model.defer="task_id" />
   <option value=""> Select a Task </option>
            @foreach($tasktypes as $task)
            <option @click="$wire.task->id = true" value="{{$task->id}}"> {{$task->name}}</option>
            @endforeach                     
</select>
    
     <div x-show="$wire.task->id"> some text here </div>
</div>

Solution

  • I think the problem is from the mixing between livewire and alpine. The context is not clear from your question, but it can be achieved several ways:

    Pure livewire:

    <div class="mt-4"> 
        <select required wire:model.defer="task_id" />
            <option value=""> Select a Task </option>
            @foreach($tasktypes as $task)
                <option value="{{$task->id}}"> {{$task->name}}</option>
            @endforeach                     
        </select>
    
        @if($task_id)
            <div> id {{ $task_id }} should appear here </div>
        @endif
    </div>
    

    or if you want it to be Alpine JS you could 'entangle' it with the livewire property:

    <div class="mt-4" x-data="{ taskId: @entangle('task_id') }"> 
        <select required wire:model.defer="task_id" />
            <option value=""> Select a Task </option>
            @foreach($tasktypes as $task)
                <option value="{{$task->id}}"> {{$task->name}}</option>
            @endforeach                     
        </select>
    
    
        <div x-show="taskId" x-html="` id ${taskId} should appear here `"></div>
    </div>