Arrange foreach loop in asc order Laravel - php

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!

Related

Laravel eager loading with two Fk to same table

I want use Eager loading in Laravel 8 with a relations of two foreign keys to the same table.
Teams table
id
name
120
Germany
245
Italy
Fixtures table
id
timestamp
home_id
away_id
winner_id
home_goals
away_goals
1
1607803200
120
245
120
2
0
Fixture Model
public function home()
{
return $this->belongsTo(Team::class, "home_id");
}
public function away()
{
return $this->belongsTo(Team::class, "away_id");
}
public function winner()
{
return $this->belongsTo(Team::class, "winner_id");
}
In controller, even with $fixtures = Fixture::with(["home", "away", "winner"])->get(); the N+1 Query detector package advise me from that problem.
Are there any way to use eager loading with multiple foreign keys belongs to the same table??
If not, any suggestions to modify the database structure in any better way?
Thank you!
UPDATED:
Add the requested info. Seen in the laravel debugbar now, I see only one duplicate query and I think it´s makes sense, are the two relations loaded in with..
So, it´s correct?
Using the data in the view:
#foreach($fixtures as $fixture)
<div class="flex items-center ">
<div>
<img class="object-scale-down h-12 w-12 border border-indigo-600" src="{{ $fixture->home->logo }}" />
</div>
<div class="flex-auto ml-5">
{{ $fixture->home->name }}
</div>
<div class="flex-auto">
</div>
<div class="flex-auto mr-5 text-right">
{{ $fixture->away->name }}
</div>
<div class="">
<div>
<img class="object-scale-down h-12 w-12 border border-indigo-600" src="{{ $fixture->away->logo }}" />
</div>
</div>
</div>
#endforeach
Data from Laravel DebugBar:

How to Handle Blade laravel [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
my controller function is. I passed data through bidder array but array data can't print
public function bidders()
{
$payments = \App\Models\Payment::all();
$posts = Post::all()->where('user_id','=',Auth::user()->id);
foreach ($posts as $post) {
$postid = $post->id;
$bidder[] = Bid::all()->where('post_id','=',$postid);
}
return view('user.student.student-post-bidders',compact('bidder','posts','payments'));
}
Here is my blade in this blade my data print from DB.
How can I print array? indexes of array print in a blade
#php
dd($bidder);
$index = 0;
#endphp
#foreach($bidder as $bid)
#foreach($posts as $post)
#if($post->id == $bid[$index]['post_id'])
<div class="row" >
<!-- Dashboard Box -->
<div class="col-xl-12" >
<div class="dashboard-box margin-top-0">
<!-- Headline -->
<div class="headline">
<h4><strong><span class="bg-danger text-center" style="margin-left: 46px">Your Post Title:</span>{{$bid[$index]->Post->title}}</strong></h4>
</div>
<div class="content">
<ul class="dashboard-box-list">
<li>
<!-- Overview -->
<div class="freelancer-overview manage-candidates">
<div class="freelancer-overview-inner">
<!-- Avatar -->
<div class="freelancer-avatar">
<div class="verified-badge"></div>
#if($bid[$index]->Tutor->profile_Image=='')
<img data-cfsrc="{{asset('asset/images/user-avatar-placeholder.png')}}" alt="" style="display:none;visibility:hidden;">
#else
{{-- {{asset('storage/app/public/profileImages/' . $pic->profile_Image)}}--}}
<img data-cfsrc="{{asset('storage/app/public/profileImages/' . $bid[$index]->Tutor->profile_Image)}}" alt="" style="display:none;visibility:hidden;">
#endif
</div>
<!-- Name -->
<div class="freelancer-name">
<h4>{{$bid[$index]->Tutor->name}}</h4>
<!-- Details -->
<strong><span>Subject:</span></strong>
#foreach($bid[$index]->Tutor->subject as $sub)
<strong><span>{{\App\Models\Subject::find($sub->pivot->subject_id)->subject}}</span></strong>
#endforeach
<!-- Rating -->
<div class="freelancer-rating">
<div class="star-rating" data-rating="{{$bid[$index]->Tutor->rating}}"></div>
</div>
<!-- Bid Details -->
<ul class="dashboard-task-info bid-info">
<li><strong id="{{ $bid[$index]->id}}">PKR:{{$bid[$index]->bid_price}}</strong><span>Fixed Price</span></li>
<li><strong>Days:{{$bid[$index]->days}}</strong><span>Delivery Time</span></li>
</ul>
<!-- Buttons -->
<div class="buttons-to-right always-visible margin-top-25 margin-bottom-0" onclick=" indexID({{$i}})">
<a href="#small-dialog-1"
onclick="moveprice({{ $bid[$index]->id}}), payment({{ $bid[$index]->id}})" class="popup-with-zoom-anim button ripple-effect"
#foreach($payments as $pay) #if($bid[$index]->post_id == $pay->post_id) id="hide" #endif #endforeach><i class="icon-material-outline-check "></i> Accept Bid</a>
{{-- #dd($bid->id)--}}
<i class="icon-feather-mail"></i> Send Message
<a id="btn" class="button gray ripple-effect ico" onclick="removeBid({{$bid[$index]->id}})" title="Remove Bid" data-tippy-placement="top"><i class="icon-feather-trash-2"></i></a>
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<span style="visibility: hidden">{{$i++}}</span>
#endif
#endforeach
#php
$index++;
#endphp
#endforeach
When I run code error will be occur
offset 1 I need all data print in a blade
How to print array index wise
you should use relations,
if you want to show the list of bidders then in bidders model
app/bidders.php
public function post()
{
return $this->belongsTo('App\Post');
}
Assuming that you have proper standards in table structure for mapping eloquent.
then you need to change your bidders function as below
public function bidders()
{
$payments = \App\Models\Payment::get();
$bidders = Bidder::whereHas('post', function($post) {
return $post->where('user_id','=',Auth::user()->id);
//Provides a filter for bidders, post which are related to user
})->with('post')->get();
return view('user.student.student-post-bidders',compact('bidders', 'payments'));
}
And there should be only one loop for bidders on blade as below.
Here is your answer why array is not appearing in blade check in comments for json_encode
#foreach($bidders as $bid)
{{$bid->id}} //gives you bid parameters
{{json_encode($bid->post)}} //this will get all the post details array/object is not printable on blade so encoded to json just for display purpose
//suppose you need only name from post then
{{$bid->post->name}};
#endforeach
This will lower your code length, as well as improve performance due to eager loading and less looping. Also removes stuff like creating array and maintain index and if condition on blade for id check.
That's it.
Happy Coding!!
I think you just need to refactoring your code ),
first of all use $bid->{$index} instead of this $bid[$index]. you have collection but you can use it as array
do you want to group your bidder by post_id ?

How to check another table's columns and get their values to the other table

i am struggling over this problem
Shortly, i have payments page. Admin selects the user and course, then he should select course_type,which gets value from courses table's three columns(cost_group, cost_minigroup, cost_individual,one of them). If course_type is selected, the cost of course must be
inserted into payments table(inside course_cost column). So what i have done
Tables:
payments{ id,student_id, course_id, course_cost}
courses { id, name,cost_group,cost_minigroup,cost_individual }
My CourseController.php
> public function get($id){
> $course = Course::findOrFail($id);
> return response()->json($course);
> }
Here is my form.blade.php
<div class="ui selection dropdown">
<input type="hidden" name="course_">
<i class="dropdown icon"></i>
<div class="default text">Course type</div>
<div class="menu">
<div class="item" data-value="course_group">Group</div>
<div class="item" data-value="course_minigroup">Mini Group</div>
<div class="item" data-value="individual">Individual</div>
</div>
</div>
My PaymentsController
public function store(){
$payment = new Payment;
$payment->student_id = Input::get('student_id');
$payment->course_id = Input::get('course_id');
$payment->course_cost = Input::get('course_cost');
$payment->save();
return redirect('payment');
}
So here is problem how to get this course_cost value out of three columns of courses table. If you know how to solve or any method or advice would be great. Thank you in advance guys.
You should better get the values by js.and in your field(drop-down) there should be this code instead
<div class="menu">
<div class="item" data-value="{{$data['course_group']}}">Your call1</div>
<div class="item" data-value="{{$data['course_minigroup']}}">Your call2</div>
<div class="item" data-value="{{$data['course_individual']}}">Your call3</div>
</div>
And then You should insert some controller code
$payment->course_cost = Input::get('course_val');
And try this on your .js file
$('.course_val').click(function({
$('#course_val').val($(this).attr('data-value'));
alert('Your alert')
}))
On your blade, I see that you named the input as course_ not so sure since the HTML snippet is incomplete, but it may be the cause of your problem.
Better try to check what are you getting before storing it to anything, try to run dd(Input::all()) first as a start for debugging.
As for getting the value of the course cost, there is a lot of approach, one is ajax the updating the fields.

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

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

Categories