Jerry Jerry - 5 months ago 10
PHP Question

Laravel/PHP - loop through items in a view

i have the following html / blade template:


{{--show all projects--}}

@if(!empty($projects))

@foreach($projects as $project)
<div class="slide">
<ul class="small-block-grid-1 medium-block-grid-3 large-block-grid-4">
<li>
<div class="thumb">
<h3 class="thumbTitle">{{$project->title}}</h3>
{{--laat maar 1 image zien --}}
@if(!empty($project->project_images))


{{ HTML::image('useruploadedimages/'.$project->project_images[0]->url) }}


@endif

</div>

</li>
</div>


@endforeach

@endif
</div>


what i want is the following: 8 projects displayed within a div with the .slide class, multiple divs with the .slide class for ervery 8 projects: for example i have 25 projects: than i want to have 4 .slide divs 3 with 8 projects and 1 with a single project...

is this even possible?

Answer

You may use array_chunck like this:

@foreach(array_chunck($projects->toArray(), 8) as $projects)
    <div class="slide">
        <ul class="small-block-grid-1 medium-block-grid-3 large-block-grid-4">
            @foreach($projects as $project)
                <li>
                    <div class="thumb">
                        <h3 class="thumbTitle">{{$project['title']}}</h3>
                        @if(!empty($project['project_images']))
                            {{HTML::image('....)}}
                        @endif
                    </div>
                </li>
            @endforeach
        </ul>
    </div>
@endforeach

Notice the array notation [] instead of object notation ->.

Comments