Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting the results in Blade foreach loop

Tags:

laravel

blade

Alright so I'm pretty new to Blade, and I did manage to get all the results that I asked for on my page. Now I want to show only 10 of the total items on my page and I seem to struggle with it, tried the array_slice without any success so far. Any suggestions?

Below the code I'm currently using

        {{--@foreach ($element['subs']->slice(0, 10) as $item)--}}

@foreach ($element['subs'] as $item)
        <div class="highlight {{ $element['class'] }}">
            <div class="el-inner-news">

                <div class="image-news">
                    <a href="{{ $item['news-item']['slug'] }}"> <img src="{{ $item['news-item']['image'] or "/assets/frontend/baywest/images/newsholder.png" }}" class="center-img" alt="{{ $item['news-item']['title'] }}" /> </a>
                </div>

                <div class="desc-news">
                    <div class="title-highlight">
                        <a href="{{ $item['news-item']['slug'] }}">{{ $item['news-item']['title'] }}</a>
                    </div>

                    <div class="text-highlight">
                        {!! $item['news-item']['textfield'] !!}
                    </div>

                    <div class="learn-more-news">
                        <a href="{{ $item['news-item']['slug'] }}">{{ $item['news-item']['read-more'] or "Learn more" }}  </a>
                    </div>
                </div>

            </div>
        </div>
    @endforeach

Thanks in advance!

like image 509
Stefan Neuenschwander Avatar asked Oct 28 '15 14:10

Stefan Neuenschwander


1 Answers

A cleaner way to do it could be this if it is a collection:

@foreach ($element['subs']->slice(0, 10) as $item)
 ...Code
@endforeach

another way for collections:

@foreach ($element['subs']->take(10) as $item)
 ...Code
@endforeach

or this if it is an array:

@foreach (array_slice($element['subs'], 0, 10) as $item)
 ...Code
@endforeach
like image 123
Mrquestion Avatar answered Dec 20 '22 19:12

Mrquestion