Hardist
Hardist

Reputation: 1993

Laravel Blade foreach loop alternating

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 class="list-group">
    <div class="list-group-item d-flex align-items-center">
        {{ $permission }}
        <span class="ms-auto">{{ $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 class="list-group">
    @foreach ($permissions as $permission)
        <div class="list-group-item d-flex align-items-center">
            @if($loop->even)
                {{ $permission }}
            @else
                <span class="ms-auto">{{ $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 class="list-group">
    <div class="list-group-item d-flex align-items-center">
        permission 1
        <span class="ms-auto">permission 2</span>
    </div>
    <div class="list-group-item d-flex align-items-center">
        permission 3
        <span class="ms-auto">permission 4</span>
    </div>
</div>

// And so on..

Upvotes: 0

Views: 450

Answers (1)

ancarofl6
ancarofl6

Reputation: 200

Doesn't something like this work?

<div class="list-group">
    @for ($i = 0; $i < count($permissions); $i = $i + 2)
        <div class="list-group-item d-flex align-items-center">
            {{ $permissions[$i] }}
            @isset($permissions[$i+1]) <span class="ms-auto">{{ $permissions[$i+1] }} </span> @endisset 
        </div>
    @endfor
</div>

Upvotes: 1

Related Questions