Limit foreach query

0

How can I limit an @foreach? I use a foreach to show the data of a related table and I would like to limit the results of that foreach I try to use this but it gives me error

{{$count = 0;}}  @foreach($product->post as $produc)  {{if($count == 4) break; }}

///contenido

{{$count++;}}

Any ideas?

    
asked by Lendy Rodriguez Silva 07.10.2018 в 22:18
source

2 answers

0

You can do it with @break :

@php
$count = 0;
@endphp

@foreach($product->post as $produc)

    @break($count == 4)

    ///contenido

    @php
    $count++;
    @endphp

@endforeach

But as an alternative you could use:

@foreach($product->post as $count => $produc)

    @break($count == 4)

    ///contenido

@endforeach
    
answered by 07.10.2018 / 22:45
source
0

If $count is always a number, I would ask you in the controller to divide that array of results into arrays of that size. Then you would pass the first array to the template.

example:

$count = 4;
$resultados = ['a', 'b, 'c', 'd', 'e','f,','g','h'];

$listas = array_chunk ($resultados, $count, true);

Now, in $ list you have an array of arrays. The first array has the first 4 elements, the second the 4 seconds, and so on.

$productos = $listas[0]; // ahora tienes los 4 primeros en $productos.

Send $ products to your template and iterate them in the foreach.

    
answered by 07.10.2018 в 22:58