Search code examples
laravelcollectionschunks

Move or equalize last elements using Laravel collection chunk method


I'm working with Laravel (9.x) collections and using chunk to split into 3 records. The last column only has one record and I need to move the last record of the previous column to the last column so that both have two.

Current result:

Current result using chunk

Expected result (Last two columns with two records each)

Expected result using chunk

How can I achieve this using Laravel Chunk or simply PHP's array functions? This is my current code:

     <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Hour</th>
                <th>Player</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($players->chunk(3) as $player)
                @foreach ($player->sortBy('index') as $detail)
                    <tr>
                        <td class="font-weight-bold">{{ $loop->parent->iteration }}</td>
                        <td>
                            {{ $detail->hour }}
                        </td>
                        <td class="text-left">
                            {{ $detail->name }}
                        </td>
                    </tr>
                @endforeach
            @endforeach
        </tbody>
    </table>

Thanks for your help.


Solution

  • Although I don't know why you need this, you can achieve this with a simple algorithm using collection's methods:

    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Hour</th>
                <th>Player</th>
            </tr>
        </thead>
        <tbody>
            @php
                $chunkedPlayers = $players->chunk(3);
                $lastChunk = $chunkedPlayers->pop();
                
                if ($lastChunk->count() === 1) {
                    $secondLastChunk = $chunkedPlayers->pop();
                    $lastChunk->prepend($secondLastChunk->pop());
                    $chunkedPlayers->push($secondLastChunk);
                }
    
                $chunkedPlayers->push($lastChunk);
            @endphp
            @foreach ($chunkedPlayers as $player)
                @foreach ($player->sortBy('index') as $detail)
                    <tr>
                        <td class="font-weight-bold">{{ $loop->parent->iteration }}</td>
                        <td>
                            {{ $detail->hour }}
                        </td>
                        <td class="text-left">
                            {{ $detail->name }}
                        </td>
                    </tr>
                @endforeach
            @endforeach
        </tbody>
    </table>
    

    See: https://laravel.com/docs/10.x/collections#available-methods