Remaining Records

1

It has a function in the Laravel ORM that does LIMIT MySQL .

What is Take and Skip .

I'm going to make three Owl Sliders on the page, one underneath the other. And the images I'm going to put come from a table in the database. I want all three carousels to have the same amount of pictures.

So I thought of doing this:

Total de Registros / 3

But this can take a tithe, for example:

10 / 3 = 3,3333333333333333

But to solve this I make a floor in PHP and it rounds to 3.

Hence it would be 3 in one line, 3 in another, and 3 in another. But I missed an image that I want to appear on the last line.

The logic would be:

$result = floor($countWorks / 3);

$slider_1 = Works::take($result)->get();
$slider_2 = Works::take($result)->skip($result)->get();
$slider_3 = Works::take($result)->skip($result + $result)->get();

I just want to know the following:

1 - Is there any other way to do this or is this the best way?

Owl Slider works like this:

<?php 
    $works = R::find('works', 'status = 1');
    $take  = array_chunk($works, 3);

    foreach($take as $work){
?>
    <div class="owl-slider-works">
        <?php 
            foreach($work as $val){
        ?>
            <div class="item">
                <img src="images/works/<?=$val->capa?>" alt="<?=$val->titulo?>">
                <div class="titulo">
                    <h5><?=$val->titulo?></h5>
                </div>
            </div>
        <?php 
            }
        ?>
    </div>
<?php 
    }
?>

Must be that way within foreach . But I do not understand how chunk will work to do this. What would it be like?

    
asked by anonymous 05.05.2016 / 13:20

1 answer

1

@Zoom, this is easy if you use the features of Collection of Laravel .

Come on. First you select all the data.

 $slider = Works::all();

Then you can use the Illuminate\Support\Collection::chunk method to "break" the results into specific pieces. In this case, let's break by 3 in 3. If you have any "leftovers", PHP will leave it in the last Collection (chunk creates other collections)

  @foreach( $slider->chunk(3) as $chunk)
      <div class="owl-slider">
       @foreach($chunk as $slide)
           <div class="item">{{ $slide->image }}</div>
        @endforeach
      </div>
  @endforeach

Better understand chunk , let's illustrate with the array_chunk function of PHP (which is used internally by Collection):

 $nomes = ['zoom', 'rray', 'wallacemaxters', 'bigown', 'randrade'];

 $de_2_em_2 = array_chunk($nomes, 2);

 print_r($de_2_em_2);

The result will be:

[
   ["zoom", "rray",],
   ["wallacemaxters", "bigown",],
   ["randrade",],
]

Note that at the end the value "randrade" was left alone, because as there were no 2 values to match, then the last group only contains the rest.

    
05.05.2016 / 13:33