Search code examples
phplaravellaravel-livewire

Display text on each iteration laravel Livewire


I need your help. Lets say I have array with 10 elements and every record to be shown on every iteration and I want to be done with Livewire, let me share with you some code and will tell you what I have tried till now.

public $content;

public $array = ['first', 'second', 'third' ,'fourth'];

foreach ($array as $item) {
    sleep(1);
    $this->content[] = "Element ${item}";
}
<div class="modal-body">
    @if ($content)
        <ul class="listree">
            @foreach ($content as $element)
                <li>
                    <div class="listree-submenu-heading">
                        {!! $element['title'] !!}
                    </div>
                    <ul class="listree-submenu-items">
                        @foreach ($element['elements'] as $sub)
                            <li>
                                <div class="listree-submenu-heading">
                                    {!! $sub['title'] !!}
                                </div>
                            </li>
                        @endforeach
                    </ul>
                </li>
            @endforeach
        </ul>
    @endif
</div>

My idea is display first record, wait 1 second, display first and second record, wait 1 second, display first, second and third records and so on... How I can do this with livewire. The problem is that $content is filled with the information after all iteration and then the component is refreshed. I tried on every iteration to send custom event which will call refresh method, but without succes. I will appreaciate any advice, and if you need more information, I will provide it.


Solution

  • Assumming you're also using alpinejs, this can be done pretty easily.

    <x-app-layout>
        <div class="text-gray-800 ml-10">
            <ul class="bg-green-200">
                <!-- The main foreach loop. -->
                @foreach (range('a', 'z') as $element)
                    <!-- render al <li> tags with display:none. -->
                    <!-- Show the 1st after 0s, the 2nd after 1s, the 3rd after 2s, ... -->
                    <li class="bg-blue-200 m-5" 
                        x-data="{show: false, index: {{ $loop->index }} }" 
                        x-init="setTimeout(() => show = true, index * 1000)">
    
                        <div x-show="show">
                            {{ $element }}
                            ...
                        </div>
    
                    </li>
                @endforeach
            </ul>
        </div>
    </x-app-layout>
    

    $loop is a special object you can access within a @foreach block.