I have a query like:
$results = Post::all();
For the sake of simplicity, let's say the output is this (by id
):
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
My website has a 5-column layout. I need to split/divide these results into 5 columns such that it ends up like this:
1 | 2 | 3 | 4 | 5
6 | 7 | 8 | 9 | 10
11 | 12 | 13 | 14 | 15
The 5 column layout is split like this (the total number of columns is 25):
<div class="row">
<div class="col-xs-5">
//
</div>
<div class="col-xs-5">
//
</div>
<div class="col-xs-5">
//
</div>
<div class="col-xs-5">
//
</div>
<div class="col-xs-5">
//
</div>
</div>
How can I split $results
up like this? Any way to make use of Laravel's Collection methods?
Try this , i think it should give you the expected result
$chunks = $results->chunk(5);
dd($chunks->toarray());
Laravel Docs
The chunk method breaks the collection into multiple, smaller
collections of a given size
also it can be used in the View like this ( keep the same query in the controller and do the splitting in the View)
EDIT
@foreach ($results->chunk(5) as $chunk)
<div class="row">
@foreach ($chunk as $test)
<div class="col-md-2">
{{ $test->id }}
</div>
@endforeach
</div>
@endforeach
Output
I think @AchrafKhouadja was right, you can use either array_chunk()
or Collection chunk()
, here is an example how to render it to be like what you've expected:
$cells = range(1, 25)
$rows = array_chunk($cells, 5);
foreach ($rows as $row) {
echo '<div class="row">';
foreach ($row as $cell) {
echo '<div class="col-xs-5">' . $cell . '</div>';
}
echo '</div>';
}
And the output would be:
<div class="row">
<div class="col-xs-5">1</div>
<div class="col-xs-5">2</div>
<div class="col-xs-5">3</div>
<div class="col-xs-5">4</div>
<div class="col-xs-5">5</div>
</div>
<div class="row">
<div class="col-xs-5">6</div>
<div class="col-xs-5">7</div>
<div class="col-xs-5">8</div>
<div class="col-xs-5">9</div>
<div class="col-xs-5">10</div>
</div>
<div class="row">
<div class="col-xs-5">11</div>
<div class="col-xs-5">12</div>
<div class="col-xs-5">13</div>
<div class="col-xs-5">14</div>
<div class="col-xs-5">15</div>
</div>
<div class="row">
<div class="col-xs-5">16</div>
<div class="col-xs-5">17</div>
<div class="col-xs-5">18</div>
<div class="col-xs-5">19</div>
<div class="col-xs-5">20</div>
</div>
<div class="row">
<div class="col-xs-5">21</div>
<div class="col-xs-5">22</div>
<div class="col-xs-5">23</div>
<div class="col-xs-5">24</div>
<div class="col-xs-5">25</div>
</div>