Alternating attributes on a page laravel

migration

Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title');
        });

controller
public function index()
    {
        $blog= Blog::all();

        return view('blog', compact('blogs'));
    }

We have something like this code on the blog page
@extends('layouts.app')

@section('content')
<div class="container">
@foreach($blogs as $blog)
    <div class="blog-list">
        <div class="blog blog--left">
            <h2 class="blog_title">{{ $blog->title }}</h2>
        </div>

        <div class="blog blog--right">
            <h2 class="blog_title">{{ $blog->title }}</h2>
        </div>
    </div>
@endforeach
</div>
@endsection

Where at the output we get:

Blog 1 (blog–left)
Blog 1 (blog–right)
Blog 2 (blog–left)
Blog 2 (blog–right)
Blog 3 (blog–left)
Blog 3 (blog–right)
Blog 4 (blog–left)
Blog 4 (blog–right)

How to make alternation so that at the exit we get:

Blog 1 (blog–left)
Blog 2 (blog–right)
Blog 3 (blog–left)
Blog 4 (blog–right)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use a modulus operator for this as long as you have the index reference.

@foreach ($blogs as $index => $blog)
    <div class="blog-list">
        @if ($index % 2 === 1) 
            <div class="blog blog--left" >
                <h2 class="blog_title">{{ $blog->title }}</h2>
            </div>
        @else

            <div class="blog blog--right">
                <h2 class="blog_title">{{ $blog->title }}</h2>
            </div>
        @endif
    </div>
@endforeach

The modulus operator here: @if ($index % 2 === 1) will always be true when the result is odd, and if it’s not odd, then it’s even which will instead print in the blog--right column.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x