Laravel: Need to solve foreach loop - php

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)).

Related

Add a block field from a specific article

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 ^.^

How to only show all articles that contains a particular value?

Currently using Laravel 8, I have to show on a page all articles but only the ones that contain a specific row value in my Database. For instance, in this one, I have a column in the desired table that is called "is_reserved" as TinyInt acting as a True or false (1-0).
I have searched absolutely everywhere and I cannot understand nor find the right syntax for filtering and show only articles that aren't reserved (is_reserved = 0).
In my blade view file, I have a #foreach loop that fetches my item from my controller, like the following below. Which works by the way, just not the way I intend it to be. I'm out of ideas.
TL:DR: I just want to be able to show all items from my database but only the ones with a specific row value.
<section class="row justify-content-evenly mt-5 mx-sm-3">
#foreach ($donations as $donation)
<article class="box col-md-5 col-sm-12 row p-3 mt-md-3 mt-sm-5 d-flex justify-content-around">
<img src="{{ $donation->image }}" alt="image" class="col" style="border-radius: 100%;">
<div class="col">
<p style="text-align: justify;">{{ Str::limit($donation->description, 80) }}</p>
<div class="d-flex justify-content-start flex-column text-left" style="width: auto; height: 100px;">
<h5>Location: Quebec</h5>
<p>Meteo: Cold</p>
<div class="row justify-content-between">
<button class="col-5 btn yellowBtn">reserve</button>
<a class="col-5 btn greenBtn" href="{{route('view-item', $donation->id)}}">View</a>
</div>
</div>
</div>
</article>
#endforeach
Move the logic to the controller / service before looping through them, then send the necessary rows to your blade (probably with a $is_reserved boolean in the array/object)
Keep in mind that if you're diving into logic in the blade / template file itself, it's best to move it back a step and just provide the template the simplest data you can.
Taking your question as an example, before sending the rows to the template, and just show the ones that match your need.
e.g.
$rows = DB::table('your_table')->where('is_reserved', '1')->get();
return $rows; //or extend your template here
Otherwise, you can ad an #if condition right to your template, and render only if ceratin condition is met

Arrange foreach loop in asc order Laravel

How do I arrange a foreach loop in ascending order with Laravel?
Here's my current code:
<h2 class="title">Top Performing Schools</h2>
#foreach($sch as $sch)
<div class="sch">
<div class="sch-content">
<a href="{{$sch->url}}">
<img style="width:60px;vertical-align: middle;" src="{{asset('images/'.$sch->logo)}}">
{{$sch->name}}
</a>
</div>
</div>
#endforeach
My guess is that $result = $result->orderBy('ranking_philippines', 'asc'); has to be put somewhere. ranking_philippines is the database field that contains the ranking data that I want the items to be sorted by.
Ok Phil, we have to do some wild guessing here. Let's presume your table is called schools and the model School.
The controller, let's call it SchoolController should look like this:
public function getRanking() {
$scores = School::orderBy('ranking_philippines', 'asc')->get();
return view('schools.ranking', compact('scores'));
}
Then in resources/views/schools/ranking.blade.php you have to get something like this:
<h2 class="title">Top Performing Schools</h2>
#foreach($scores as $score)
<div class="sch">
<div class="sch-content">
<a href="{{$score->url}}">
<img style="width:60px;vertical-align: middle;" src="{{asset('/images/'.$score->logo)}}">
{{$score->name}}
</a>
</div>
</div>
#endforeach
I hope that gives you some help. You have to help us too Phil by being more specific. No offense. I understand. Good luck with your project!

Laravel 5.2 - How to echo a field from a relationship

Im trying to echo the categoryid field from the with('categorys').
My appserviceprovider:
view()->composer('welcome' , function($view){
$view->with('homerings', Ring::where('homepage', '=', 1)->with('categorys')->get()->all());
});
Where i'm trying to echo it in welcome.blade.php.
#foreach($homerings as $ring)
{{ dd($ring->categorys) }}
<div class="col-md-3 col-sm-6 col-xs-6">
<a href="">
<img class="img-responsive homepage-ring" src="{{url($ring->image)}}" alt="{{$ring->title}}">
</a>
</div>
<?php
$i++;
?>
#if($i == 4)
</div>
<div class="row">
#endif
#endforeach
Normal i think it should work like:
{{ dd($ring->categorys->categoryid) }}
But this is not working.
the error:
Undefined property: Illuminate\Database\Eloquent\Collection::$categoryid (View: /resources/views/welcome.blade.php)
As your error tells you "Undefined property ...Collection::$categoryid". It means you are trying to access the categoryid property of a Collection object instead of a Category object.
When you defined a relationship where many can be returned (like hasMany()), Eloquent will return a Collection (more than one) of results. When you define an one-to-one relation, eloquent will return only one result and therefore the Model it is related to.
To retrieve the first model in you collection you could do something like:
$category = $ring->categorys()->first(); // Get first
echo $category->categoryid;
However since your relation will return many I think you would like to have something like:
$categories = $ring->categorys; // Get all categories
#foreach ($categories as $category) // Loop
{{ $category->categoryid }} // Echo categoryid
#endforeach
Hope this helps :)
Ps: the plural form of category is categories

How to display latest('updated_at') records in blade file of laravel

I am doing project in laravel. In my project there are two tables categories and subcategories. subcategories table has categoryid as foreign key.
subcategoryModel.php has following function
public function category(){
return $this->belongsTo('App\Category');
}
In my blade file I am displaying my subcategories using category object as follows,
blade.php
<div class="col-sm-6 col-align-left">
#foreach($category as $c)
<div class="form-group clearfix">
#if($c->subcategories->count() > 0)
<h4><b>Subcategories: </b></h4>
<div class="form-group clearfix">
#foreach($c->subcategories as $subcategory)
<h4>{{$subcategory->subcategoryname}}</h4>
#endforeach
</div>
#endif
<h4>Add Subcategories</h4>
</div>
#endforeach
</div>
This display correct data,but now I want to display data in the order they are updated/created. Is there any way to display data as per the requirement?
I want to something into the blade file itself. How to do this? Please give suggestions.
You shouldn't do something like that in a blade. Blade should be kept as dumb as possible. Main things should be done in the controller and then passed to the blade. you can do this in your controller:
$categories = Category::with(array('subcategories' => function($query) {
$query->orderBy('created_at', 'DESC');
}))->get();
now the subcategories in the category object will be ordered.
#foreach($c->subcategories()->orderBy('updated_at','asc')->get() as $subcategory)
<h4>{{$subcategory->subcategoryname}}</h4>
#endforeach
Edit: I do like the other answer however OP asked for within the blade file itself

Categories