0

I have a grid that has three columns per row. I would like to add an advertisement every row but randomly placed (could be placed on the first, second or third column). I have used this answer to create the grid Loop row in bootstrap every 3 columns but every time that I have tried ends up showing the advertisement but jumps one of the giveaways.

$numOfCols = 3;
$rowCount = 0;
$bootstrapColWidth = 12 / $numOfCols;

<div class="row">
@foreach($giveaways as $key => $giveaway)
    @if($key == 0 || $key == 3 || $key == 6)
        ADS HERE
    @else
        <div class="col-sm-{{ $bootstrapColWidth }} text-center">
            SHOW GIVEAWAY
        </div>
    @endif

    <?php
        $rowCount++;
        if($rowCount % $numOfCols  == 0){
            echo '</div><div class="row" style="margin-top: 5px; margin-bottom: 5px;">';
        }
    ?>
@endforeach
</div>

At the example above I have tried using the most right square to display the adversitesement but I would like it to be a random column.

Example how I would like to end up in the end example

Bruno Francisco
  • 3,841
  • 4
  • 31
  • 61
  • Maybe to try to export already made collection then just make one foreach loop in blade file. This is just idea, like [`chunk()`](https://laravel.com/docs/5.5/collections#method-chunk) `$giveaways` into portions of two elements. Then add an ad element to every chunk, then shuffle those small arrays, then collect it back to collection with all preformed elements including ads on random positions. – Tpojka Feb 11 '18 at 23:04
  • @Tpojka I have tried using this method: https://pastebin.com/raw/C2a0cLHV and you can see in the code that at the end the "ADS" is not present in the array. Could you tell me what I am doing wrong?! – Bruno Francisco Feb 12 '18 at 13:52
  • Try with passing variable by reference in the loop: `foreach($giveaways as &$chunk){`. This way new value should persist. – Tpojka Feb 12 '18 at 14:41
  • By the help of a friend I have managed to do it adding this: `$giveaways[$key] = $chunk;` but this returns an array and not the collection itself. I would like to return the collection because I'm using a method that is contained in the `Giveaway Model`. You model of trying by reference doesn't update the `$giveaway` collection – Bruno Francisco Feb 12 '18 at 15:15
  • You can try with `collect($array)` method on given array. [Docs](https://laravel.com/docs/5.5/helpers#method-collect). – Tpojka Feb 12 '18 at 15:56
  • Do you mind leaving an answer? I could accept it since this solved my problem – Bruno Francisco Feb 12 '18 at 16:02
  • I just gave you some idea pointers how to solve it. Feel free to write an answer yourself describing fully how achieved solution. Also keep in mind that this will work on 3 elements only. In addition you can pass one more argument/variable determining how many elements in each row you need. #SOreadyToHelp – Tpojka Feb 12 '18 at 16:25

0 Answers0