First of all, English is not my primary language and if the group in
term is wrong for what I'm trying to say, please warn.
This method is actually all about templating. I am going to use Laravel Tricks as an example. Did you ever come across a situation where every row of those tricks are a different div
which has 3 divs
for each trick. Sample HTML is below:
<div class="row>
<div class="trick"> ... </div>
<div class="trick"> ... </div>
<div class="trick"> ... </div>
</div>
<div class="row">
<div class="trick"> ... </div>
<div class="trick"> ... </div>
<div class="trick"> ... </div>
</div>
<div class="row">
<div class="trick"> ... </div>
<div class="trick"> ... </div>
<div class="trick"> ... </div>
</div>
In that situation you have to do things like:
@foreach ($tricks as $index => $trick)
{{-- for every 1st, 4th, 7th ... element, begin row --}}
@if ($index % 3 === 0)
<div class="row">
@endif
{{-- actual HTML of each trick here --}}
{{-- for every 3rd, 6th, 9th ... element, end row --}}
@if ($index % 3 === 2)
</div>
@endif
@endforeach
/*
* OR
*/
<div class="row">
@foreach ($tricks as $index => $trick)
{{-- for every 4th, 7th, 10th ... element, end previous row and begin a new one --}}
@if ($index % 3 == 0 && $index != 0)
</div><div class="row">
@endif
{{-- actual HTML of each trick --}}
@endforeach
</div>
Of couse, this is not the actual case but what I'm trying to say is, wouldn't it be easier if you could just do this:
@foreach ($tricks->groupIn(3) as $trickGroup)
<div class="row">
@foreach ($trickGroup as $trick)
{{-- actual HTML of each trick --}}
@endforeach
</div>
@endforeach
I just come across a situation where I can achieve it elegantly with this groupIn
method and also this is what AngularJS uses for situations like those and I just wanted to get your opinion about it.
I'd suggest writing your own html helper function for such situations. I wouldn't put in a model or php class, unless required.
If you see the need for this across multipe models, maybe think of using a Trait (re-usable methods for classes).
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community