Home > front end >  Laravel loop collection into small chunks
Laravel loop collection into small chunks

Time:10-22

@foreach ($allbulletin as $bullets)
    @if ($loop->first)
        {{$bullets->title}}
    @endif

    @if ($loop->last)
        {{$bullets->title}}
    @endif
@endforeach

I want to loop the following title of 10 into two columns. When I try this snippet, it gets me the first and last titles. What I really want is to break the result 10 in 5 of two columns.

CodePudding user response:

you can use collection chunk method

<div class="row">
    @foreach ($allbulletin->chunk(5) as $chunk)
        <div class="col-md-6"
            @foreach ($chunk as $bullet)
                <p>{{ $bullet->title }}</p>
            @endforeach
        </div>
    @endforeach
</div>

CodePudding user response:

Another possible solution is to avoid breaking the results at server side to let the browser perform this job.

This way you can simply loop over your results with a @foreach statement:

@foreach ($allbulletin as $bullets)
  <div class="content">
        {{$bullets->title}}
  </div>
@endforeach

Then you can display it using flex-box (CSS) as in the following snippet.

.container {
  display: flex;  
  flex-wrap: wrap;
  width: 200px;
  background-color: lightgrey;
}

.content {
  width: 80px;
  margin: 10px;
  background-color: orange;
}
<div class="container">
  <div class="content">#1</div>
  <div class="content">#1</div>
  <div class="content">#1</div>
  <div class="content">#1</div>
  <div class="content">#1</div>
  <div class="content">#1</div>
  <div class="content">#1</div>
  <div class="content">#1</div>
  <div class="content">#1</div>
  <div class="content">#1</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use this simple array_chunk() method:
According to documentations:array_chunk, it will automatically make array chunks according to given value

$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 5, true));

Output will be like this:

Array ( [0] => Array ( [0] => a [1] => b [2] => c [3] => d [4] => e ) )
  • Related