Php foreach Laravel中至少3个元素

Php foreach Laravel中至少3个元素,php,laravel,Php,Laravel,我有一个集合,其中最多可以有3个元素。可以是1个元素,也可以是2个元素。若我只有一个元素,或者集合中有两个元素,我需要检查它并添加html 我的代码: @foreach($collections->take(3)->get() as $collection) {{ $collection->name }} @if($collections->count() == 1) <div>empty</div> @end

我有一个集合,其中最多可以有3个元素。可以是1个元素,也可以是2个元素。若我只有一个元素,或者集合中有两个元素,我需要检查它并添加html

我的代码:

@foreach($collections->take(3)->get() as $collection)
    {{ $collection->name }}
    @if($collections->count() == 1)
       <div>empty</div>
    @endif
    @if($collections->count() == 2)
       <div>empty</div>
       <div>empty</div>
    @endif
@endforeach
或者,如果集合中有2个元素,则需要获取结果:

Collection name
Collection name
empty
如果我的集合中有3个元素,我需要得到:

Collection name
Collection name
Collection name

我如何做到这一点?

我看不出当前代码无法工作的原因,但您可以尝试以下方法

按原样循环3限制的集合,然后运行
for
循环-如果
$collections->count()
为2,则
3-2=1
,这样就得到了for循环的1次迭代。如果计数为3或更高,则
for
循环的条件永远不会为真,并且不会打印任何内容

@foreach($collections->take(3)->get() as $collection)
    {{ $collection->name }}
@endforeach

@for ($i = 0; $i < 3 - $collections->count(); i++) 
     <div>empty</div>
@endfor
@foreach($collections->take(3)->get()作为$collection)
{{$collection->name}
@endforeach
@对于($i=0;$i<3-$collections->count();i++)
空的
@结束

您当前的输出是什么
@elseif
感觉是个好主意。条件块不应该在循环之外吗?
@foreach($collections->take(3)->get() as $collection)
    {{ $collection->name }}
@endforeach

@for ($i = 0; $i < 3 - $collections->count(); i++) 
     <div>empty</div>
@endfor