Home > database >  Laravel Blade foreach loop alternating
Laravel Blade foreach loop alternating

Time:11-05

So I have a list of permissions I wish to display for a user in a list group. The thing is, I do not want to display them stacked one below another, but in two lists rather. It is better with examples. The below is how I want it to be displayed:

List Group

Only the "catch" is this. Here is my code:

<div >
    <div >
        {{ $permission }}
        <span >{{ $permission }}</span>
    </div>
</div>

I am unsure of how to "alternate" the display of the permissions. I have tried with using $loop->even and $loop->odd, but that will give me results like this:

Bad results

The code I used is this:

<div >
    @foreach ($permissions as $permission)
        <div >
            @if($loop->even)
                {{ $permission }}
            @else
                <span >{{ $permission }}</span>
            @endif
                </div>
            @endforeach
    </div>
</div>

I could split the collection in two in my controller but I cannot really use the list group code that I have above to loop over two collections because results will be displayed twice.

Any pointers in the right direction would be greatly appreciated, and ideally I would like to have the results displayed as below:

<div >
    <div >
        permission 1
        <span >permission 2</span>
    </div>
    <div >
        permission 3
        <span >permission 4</span>
    </div>
</div>

// And so on..

CodePudding user response:

Doesn't something like this work?

<div >
    @for ($i = 0; $i < count($permissions); $i = $i   2)
        <div >
            {{ $permissions[$i] }}
            @isset($permissions[$i 1]) <span >{{ $permissions[$i 1] }} </span> @endisset 
        </div>
    @endfor
</div>
  • Related