Add a block field from a specific article - php

I have an article, each article has article_blocks, the blocks have a video_link field
And I need to display this field in the list of articles
This is how the article list output is roughly implemented
<div class="blog-list">
#foreach($articles as $article)
<div class="blog-article">
<div class="video-button video-modal-button-blog" data-video="https://www.youtube.com/embed/{{ $article_block->video_link }}">
<span>Watch video</span>
</div>
<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>
Each article has a button to open a video, but this video field itself is not in the article itself, but in the article blocks
I now take this field from the block and output it, it turns out like this
<?php
use App\Models\ArticleBlock;
$article_block = ArticleBlock::whereNotNull('video_link')->first();
?>
<div class="blog-list">
#foreach($articles as $article)
<div class="blog-article">
#if ($article_block->video_link !== 'null')
<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
<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>
As a result, I get this field with video and it is displayed, but the same video is displayed for all articles in the list, and each article should have its own field and its own video. How can this be fixed?
I probably need to look for something like blocks by article id
$article_block = ArticleBlock::where('article_id', $article->id)->whereNotNull('video_link')->first();
But I can't get id

Cant write comment, under 25 rep :(
data-video="https://www.youtube.com/embed/{{ $article_block->video_link }}"
This looks wrong. You should eager load article blocks (eager loading is generally faster than lazy loading) for all articles with a with statement in your eloquent query see: https://laravel.com/docs/8.x/eloquent-relationships#eager-loading
Then if everything is correct you should be able to do just {{ $article->block->video_link }} or something similar.
Above is right if article has only one article block (one to one relationship).
But it seems that article has multiple blocks (one to many relationship) so you would need to iterate over each of the article block as well with another #foreach statement.
#foreach($articles as $article)
#foreach($article->article_blocks as $block)
<p>URL of video is: https://www.youtube.com/embed/{{ $block->video_link }}</p>
#endforeach
#endforeach
Now lets answer your question why video is same everywhere? Because you've coded it as so. You should NEVER write custom queries in your blade files.
Here i am referring to this part of your code:
<?php
use App\Models\ArticleBlock;
$article_block = ArticleBlock::whereNotNull('video_link')->first();
?>
Queries should be either in controllers/services or repositories.
$article_block = ArticleBlock::whereNotNull('video_link')->first();
will just give you first article block defined in ur database where video_link is not null. It won't guarantee that ArticleBlock belongs to given Article.
Lets hope that i put you on the right path ^.^

Related

Counting All articles using withCount()

I am using withCount() to count the number of articles in a category, everything works well.
The question is how to count and display the number of articles for All categories?
Controller
$categories = BlogCategory::withCount('articles')->get();
blade.php
<div class="blog-filter">
<div class="blog-filter__item active" data-filter="all">All</div>
#foreach($categories as $category)
<div class="blog-filter__item" data-filter=".category_{{$category->id}}" value="{{ $category->title }} ({{ $category->articles_count }})">{{ $category->title }} ({{ $category->articles_count }})</div>
#endforeach
</div>
({{ $category->articles_count }}) responsible for counting articles
you can use count method:
$allArticlesCount=Article::query()->count();
and do not forget to send it to your view as well.
a better approach is to get the count directly form the result you already got from db like #Apuv Bhavsar in his comment:
$allArticlesCount = $categories->sum('articles_count');
unless you have some conditions to apply this approach reduce the trips count to DB.

Pagination Link

What is the correct way to call the "Links" function after this "Foreach"?
I don't know how to handle the variable to put in function.
#inject('usuarios', 'App\User')
#foreach($usuarios->getIndicados() as $user)
#endforeach
<div class="row">
<div class="col-12 text-center">
{{ $usuarios->getIndicados()->links() }}
</div>
</div>
Maybe it's just an editing error, but in your output the -tags don't seem to be closed again. Also, there should be no space like < a> at the beginning of the tag. And < a hr_ef= ... is obviously wrong.
In order to style them, you can add a class attribute to the tags while building the string and do the style-stuff in css.
This is what laravel document provides. You need to add links in the collection.
<div class="container">
#foreach ($users as $user)
{{ $user->name }}
#endforeach
{{ $users->links() }}

Get custom post type fields through a repeater

I'm in a WP project. I created a custom post type called Team Members
I also created a custom field block with a field called contact_members which is a repeater and has two sub-fields called location_map and member. This member sub-field is related with the custom post type team member.
I have no issues with getting the location_map.
The issue is that I can't get the post type fields. (coming from contact_members->member->post type
<?php
$members = get_field('contact_members');
?>
#foreach($members as $member)
<div class="member {{ $member['location_map'] }}">
<img class="map" src="{{ get_the_post_thumbnail_url($member['member']->ID) }}">
<h3>{{ get_the_title($member['member']->ID) }}</h3>
<p class="position">{{ $member['member']->position }}</p>
<p class="location">{{ $member['member']->location }}</p>
Contact
</div>
#endforeach
On a first look i cant see any problems with your code. What i consider the most possible senario is ( since that i guess you are using the ACF plugin ) the $member['meber'] variable holds the (int) post_id and not the Post Object. Have you tried var_dump() ?
Cheers!
I found the answer, I should put [0] after $member['member'], in order to reach the array's first element and after that I can finally go after what I want from the object, so:
<?php $members = get_field('contact_members'); ?>
#foreach($members as $member)
<div class="member {{ $member['location_map'] }}">
<img class="member-image" src="{{ get_the_post_thumbnail_url($member['member'][0]->ID) }}">
<h3 class="member-name">{{ $member['member'][0]->post_title }}</h3>
<p class="position">{{ $member['member'][0]->position }}</p>
<p class="location">{{ $member['member'][0]->location }}</p>
Contact
</div>
#endforeach

Laravel: Need to solve foreach loop

What i'm trying to do is basically have the "latest" episodes show for a series that is has a status of "ongoing" below is the code i have so far.
The problem i a facing is that I can't seem to make the foreach loop for episodes work for the series. Wit hthe current code what it does is shows the same variables. Rather what i think is happening is that it loops the same query for each series so that the same variable pops up for each series.
Can anyone help me out here?
Also the way the episodes are linked is by using the title_id for the titles so in the table for episodes, they are liked by 'title_id', I wouldn't know what to do with that in this sequence though.
<?php $titles = DB::table('titles')->whereNotNull('poster')->where('status', '=', 'ongoing')->orderBy('updated_at', 'desc')->limit(12)->get(); ?>
#foreach ($titles as $title)
<?php $episodes = DB::table('episodes')->orderBy('created_at', 'desc')->limit(1)->get(); ?>
#foreach ($episodes as $episode)
<figure class="col-lg-2 col-md-3 col-sm-4 pretty-figure">
<div class="home-episode-number">
{{ $episode->episode_number }}
</div>
<div class="flip-containerw">
<div class="flipper">
<img src="{{ $episode->poster ? $episode->poster : '/assets/images/noimageepisode.png' }}" alt="" class="img-responsive">
</div>
</div>
<div class="home-anime-name">
{{ str_limit($title->title, 23, '...') }}
</div>
</figure>
#endforeach
#endforeach
You are not following some basic design patterns, like, for instance, the Model-View-Controller structure.
MVC
It's not good practice to have DB calls inside your view, wich you are doing. You should do it inside your model, or in a repository. And pass it trought the controller.
You would avoid a lot of headache if you start using eloquent properly.
Eloquent
Now, answering your question:
If you want to get the episode for the title in the loop, try using a where:
$episodes = DB::table('episodes')->where('title_id,'=',$title->id)->orderBy('created_at', 'desc')->limit(1)->get();
That query will retrieve just one episode (limit(1)).

Included blade template repeating in each foreach loop iteration

I'm using Blade templating with Laravel and I'm trying to use a #foreach loop to display notifications. The problem is that if I have say 10 notifications, the first notification is repeated 10 times.
The code to output each notification:
#foreach ( Auth::user()->unreadNotifications as $notification )
{{ $notification->type->web_template }}
{{ $notification->id }}
#include($notification->type->web_template)
#endforeach
web_template will output a path to the template: notifications.web.user_alert
For each iteration of the loop the {{ $notification->type->web_template }} and {{ $notification->id }} will output what they're supposed to but #include($notification->type->web_template) will only output the first notification each time.
So the output will look like:
156 notification.web.new_message
You have a new message from Joe.
154 notification.web.user_alert
You have a new message from Joe.
145 notification.web.new_like
You have a new message from Joe.
I think it's some sort of cache issue maybe, but I couldn't find anyone with the same problem.
Any ideas?
UPDATE: Adding some code
Example notification view:
#extends('layouts.notification-wrapper')
#section('url', url('jobs/'.$notification->job_id.'#highlight'.$notification->bid_id))
#section('image', '/assets/img/no-photo.jpg')
#section('header', $notification->collector->firstname . ' ' . $notification->collector->secondname)
#section('description')
has placed a bid of €{{ number_format($notification->bid()->withTrashed()->first()->amount,0) }} on your job.
#stop
Notification wrapper:
<li #if(!$notification->read)
class="unread"
#endif>
<a href="#yield('url')" data-id="{{ $notification->id }}">
<div class="pull-left">
<img src="#yield('image')" class="img-circle" alt="user image">
</div>
<h4>
#yield('header')
<small><i class="fa fa-clock-o"></i> {{ $notification->created_at->diffForHumans()}}</small>
</h4>
<p> #yield('description')</p>
</a>
</li>
Answering my own question!
Found this: Laravel Blade Templates Section Repeated / cache error
Basically whatever way it works I need to overwrite my sections when looping and using #yield... I think. So I need to replace #stop with #overwrite in my views.

Categories