John Davidson

php - Limit output to one block

0 comments
Message:


I have a page listing all articles. Each article has video blocks, and I add this video to the button for a specific article


<div class="blog-list">
@foreach($articles as $article)
<div class="blog-article">

@foreach($article->articleBlocks as $article_block)
@if($article_block->type === \App\Models\ArticleBlock::TEXT_VIDEO)
<div class="video-button video-modal-button-blog" data-video="https://www.youtube.com/embed/{{ $article_block->video_link }}">
<span>Watch video</span>
</div>
@endif
@endforeach

<h2 class="blog-article__title">{{ $article->title }}</h2>
<span>{{ date('d F Y', strtotime($article->published_at)) }}</span>
<span>{{ $article->getTotalViews() }} Views</span>
</div>
@endforeach
</div>

This cycle begins


@foreach($article->articleBlocks as $article_block)

I have 4 types of blocks, and before displaying a block with a video, I need to define it


@if($article_block->type === \App\Models\ArticleBlock::TEXT_VIDEO)

But the problem is that an article may have several such blocks with video, and then several such buttons are displayed in the code, depending on the number of blocks


I need to limit the output to only one block, preferably the very first


I tried to use $loop->first, but it displays the first video for the first article in the list, and the rest is empty


Are there any other options?



My Answer:
To limit the output to one block for each article, you can use a flag variable to keep track of whether a video block has already been added for that article. Here's an example code snippet in PHP:

php
$articles = [
['title' => 'Article 1', 'video' => 'video1.mp4'],
['title' => 'Article 2', 'video' => 'video2.mp4'],
['title' => 'Article 3', 'video' => 'video3.mp4'],
// Add more articles here
];

foreach ($articles as $article) {
$videoAdded = false; // Flag variable to track if video block has been added

echo '

' . $article['title'] . '

';

// Check if video block has already been added for this article
if (!$videoAdded) {
echo '
';
echo '';
echo '
';

$videoAdded = true; // Set flag to true after adding video block
}

// Add other content for the article here
}


In this code snippet, we iterate through each article in the `$articles` array and check if a video block has already been added for that article using the `$videoAdded` flag variable. If a video block has not been added yet, we add the video block and set the flag to true. This way, only one video block will be added for each article.

Rate this post

3 of 5 based on 1085 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us