Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

n1smo's avatar
Level 2

Dynamicly duplicating livewire components in alpine template.

Hi, is there a way to dynamically duplicate livewire components in an alpine template loop?

I have setup similiar to this, an alpine template loop, where positions can be added or removed by alpine: <template x-for="(position, index) in positions" :key="position.id"> <livewire:media-library wire:model="myUpload" /> </template>

This works fine with other fields inside this template like this: <input type="hidden" :name="'positions[' + index + '][media_id]'" :value="position.media_id"> But not with the livewire component, because it does not get a unique id. Tried this, but its now working:

<livewire:media-library :wire:key="'media-library-' + index" />

Any idea how to set the wire:key dynamically?

0 likes
3 replies
geowrgetudor's avatar

It won't work. It might work if you wrap your livewire component inside a blade component, give it a try.

valentin_vranic's avatar

So basically you can't generate livewire components dynamically via Alpinejs, because they are rendered on page load, and with Alpine, you can't append like that, because by default they won't re-render the page.

However If I can suggest a solution (for sure there can be different, better ones), with what I came up.

It is to combine it with wire:click or something similar to add new entry to an array (with methodically generated index values), and then because of property update the view will update too, and in that case you could loop trough it. And add the :key to the livewire component itself.

<div class="row mb-2 border-bottom pb-2" x-data="managePrefixes">
    @foreach($positions as $posKey => $position)
	   <livewire:media-library
                :key="'prefix-cli-' . $posKey"
                 wire:model="myUpload"
        />
    @endforeach
</div>

hope you could use it for your solution

Please or to participate in this conversation.