I am building a blog in Laravel but I found a problem in my blog template, from the routes file I send the post variable by compact:
Route::get('/blog', function () {
$posts = App\Post::latest('published_at')->get();
return view('blog', compact('posts'));
});
and from the view I implement a @foreach
:
<!-- Blog -->
<div class="section blog-posts" id="blog-section">
@foreach($posts as $post)
<div class="row">
<div class="col col-m-12 col-t-6 col-d-6">
<div class="blog_item animated">
<div class="image">
<a href="blog-page.html"><img src="mcard/images/blog/blog1.jpg" alt="" /></a>
</div>
<div class="content-box">
<div class="i_title">
<div class="icon"><strong>{{ $post->published_at->format('d') }}</strong> {{ $post->published_at->format('M') }}</div>
</div>
<div class="category_bts">
@foreach($post->tags as $tag)
<a href="#" class="category">#{{ $tag->name }}</a>
@endforeach
</div>
<a href="blog-page.html" class="name">{{ $post->title }}</a>
<p>
{{ $post->excerpt }}
</p>
<a href="blog-page.html" class="btn btn_animated"><span class="circle">Leer más</span></a>
</div>
</div>
</div>
<div class="col col-m-12 col-t-6 col-d-6">
<div class="blog_item animated">
<div class="image">
<a href="blog-page.html"><img src="mcard/images/blog/blog1.jpg" alt="" /></a>
</div>
<div class="content-box">
<div class="i_title">
<div class="icon"><strong>{{ $post->published_at->format('d') }}</strong> {{ $post->published_at->format('M') }}</div>
</div>
<div class="category_bts">
@foreach($post->tags as $tag)
<a href="#" class="category">#{{ $tag->name }}</a>
@endforeach
</div>
<a href="blog-page.html" class="name">{{ $post->title }}</a>
<p>
{{ $post->excerpt }}
</p>
<a href="blog-page.html" class="btn btn_animated"><span class="circle">Leer más</span></a>
</div>
</div>
</div>
</div>
@endforeach
</div>
The problem is that for each row (row) there should be 2 posts and if I place the foreach where I am placing it, for each row I would repeat the same post twice.
It is solved as follows:
That is, the segment
What it does is split the $posts array and place it 2 by 2 in another array called $post, that is why this other segment must be placed later
Where that arrangement that goes from 2 to 2 we will go through it from 1 to 1 so that it adapts to the template.
And why don't you simply iterate inside the row printing columns? When the columns exceed the limit of 12 units, they should be printed below, visually indicating that it is another row, if you have empty spaces and the columns are not filled properly, it would already be a problem of your styles. For what you are doing, your posts should have the same height and if they don't, it would be, in my opinion, bad interface design.
Your code should look like this: