Laravel视图中PHP数据列表按4列横向排列布局求助
Hey there! I see exactly what's going wrong here—right now, you're generating a full .row for every single penpal in your loop, which is why you're getting that vertical repetition instead of 4 items side-by-side per row. Let's fix this by properly chunking your data and filling each column in order.
The Core Issue
Your current code creates a new .row with 4 columns every time it loops through one penpal, but only the first column gets populated. This means each penpal takes up an entire row by itself (with 3 empty columns), leading to the stacked vertical layout you don't want.
The Solution: Use Collection Chunking
Laravel's collections have a handy chunk() method that lets you split your $penpals into groups of 4. Each group will correspond to one .row, and we'll loop through each item in the group to fill the columns properly.
Here's the revised Blade code:
{{-- Split penpals into groups of 4 to create rows --}} @foreach($penpals->chunk(4) as $penpalGroup) <div class="row"> {{-- Loop through each penpal in the group to build columns --}} @foreach($penpalGroup as $penpal) <div class="col-md-3 mb-4" style="border:1px solid red"> <table border> <tr style="border:1px solid red"> <td> {{-- Simplified image fallback logic --}} <a href="#"> <img src="{{ $penpal->image ?? asset('data/ProjectImages/master/logoImage/6.png') }}" alt="Penpal Profile" style="max-width: none; height: 170px; display: inline;" height="170px" width="170px" class="img-thumbnail" > </a> </td> </tr> <tr class="text-center"> <td> {{ $penpal->user->name }} {{-- Gender icon with dynamic path --}} <img src="{{ asset('data/ProjectImages/master/' . ($penpal->user->gender == 'men' ? 'men.png' : 'women.png')) }}" alt="{{ ucfirst($penpal->user->gender) }}" > {{ $penpal->user->age }} {{-- Country icon with dynamic path --}} <img src="{{ asset('data/ProjectImages/master/' . ($penpal->user->country == 'ko' ? 'korea.png' : 'japan.png')) }}" alt="{{ strtoupper($penpal->user->country) }}" > </td> </tr> </table> </div> @endforeach </div> @endforeach
Key Improvements Explained
chunk(4): This splits your$penpalscollection into smaller groups of 4 items. Each group becomes one row in your layout, so you'll never have empty columns cluttering up the page.- Responsive Columns: Using
col-md-3(a Bootstrap class) ensures each column takes up exactly 1/4 of the row width on medium and larger screens (since Bootstrap uses a 12-column grid: 12 ÷ 4 = 3). Swap it forcol-sm-3orcol-3if you want the 4-column layout to apply to smaller screens too. - Cleaner Logic: I simplified repetitive image paths using ternary operators and the null coalescing operator (
??) to cut down on duplicate code and make the template easier to maintain. - Spacing: The
mb-4class adds margin between rows, making the layout look more polished.
内容的提问来源于stack exchange,提问作者박보근

