如何在Laravel中实现collection条目两列并排展示且内容唯一不重复
问题原因
你当前的代码在遍历每一条$property时,都会渲染两个完全相同的卡片绑定同一条数据,所以自然会出现同一行两列展示同一条数据的问题。
方案1:使用Laravel Collection的chunk方法手动分组
Laravel集合自带的chunk方法可以将数据集按指定数量拆分成多个子集,你可以按每组2条拆分,每组对应一行,再在组内遍历输出单个卡片即可:
{{-- 外层容器只保留一次,不要写在循环内 --}} <div class="mt-4 lg:gap-6 lg:flex lg:items-center lg:flex-wrap lg:mt-20"> @forelse ($properties->chunk(2) as $propertyChunk) <div class="flex w-full gap-6"> {{-- 行容器,每行放2个卡片 --}} @foreach ($propertyChunk as $property) <div class="flex-1 p-4 bg-white rounded-lg"> {{-- 单个卡片,只写一次 --}} <div class="p-6"> <h4 class="text-2xl font-bold cursor-pointer"> {{$property->address1}} @if(!$property->address2==null) ,<br/>{{$property->address2}} @endif </h4> <div class="mt-2"> <span class="text-xl font-extrabold text-blue-600">@money($property->valuation, 'ZAR')</span> /M </div> <div class="flex mt-2"> Tenant<br> {{$property->user->name}} </div> </div> <div class="flex justify-between p-4 text-gray-700 border-t border-gray-300"> <div class="flex items-center"> </div> </div> </div> @endforeach </div> @empty <p class="w-full">No Properties to show</p> @endforelse </div>
这种方案可以精准控制每行的条目数量,就算最后一组只有1条数据也能正常展示。
方案2:用CSS自动排版(更简单)
如果你不需要手动控制行逻辑,直接用Tailwind的网格布局让浏览器自动排列卡片即可,不用修改集合遍历逻辑:
{{-- 外层用网格布局,大屏自动分两列 --}} <div class="mt-4 lg:mt-20 grid grid-cols-1 lg:grid-cols-2 gap-6"> @forelse ($properties as $property) <div class="p-4 bg-white rounded-lg"> {{-- 单个卡片只写一次 --}} <div class="p-6"> <h4 class="text-2xl font-bold cursor-pointer"> {{$property->address1}} @if(!$property->address2==null) ,<br/>{{$property->address2}} @endif </h4> <div class="mt-2"> <span class="text-xl font-extrabold text-blue-600">@money($property->valuation, 'ZAR')</span> /M </div> <div class="flex mt-2"> Tenant<br> {{$property->user->name}} </div> </div> <div class="flex justify-between p-4 text-gray-700 border-t border-gray-300"> <div class="flex items-center"> </div> </div> </div> @empty <p class="col-span-full">No Properties to show</p> @endforelse </div>
这种方案代码更简洁,适配响应式的成本更低。
内容的提问来源于stack exchange,提问作者Kobs
相关产品推荐
相关产品推荐

