foreach with every 10th and 2nd changes - php

So i am dealing with coupons that I need to print. I prepared the view and I am passing coupons to the view:
public function printSelected($ids){
$couponIDs = explode(',', $ids);
$selectedCoupons = Coupon::find($couponIDs);
return view('admin.coupons.print')->with(compact('selectedCoupons'));
}
Now I need to loop through them in a certain manner.
every 10 coupons I need a new "page" block because 10 coupons fit into a page block
every second coupon I need a new table row because 2 coupons or table data fits into one row

There are multiple ways to do this but I find it very readable to use the chunk method of the Collection object. Another option would be to use modulus ($index % 10 === 0).
<div class="coupons">
{{-- Create chunks of 10 as this is the max per page --}}
#foreach($selectedCoupons->chunk(10) as $pageCoupons)
<div class="page">
<div class="subpage">
<table>
{{-- Create chunks of 2 so every row is filled with up to 2 coupons --}}
#foreach($pageCoupons->chunk(2) as $rowCoupons)
<tr>
{{-- Loop over the row coupons to create the columns --}}
#foreach($rowCoupons as $coupon)
<td>
<span class="coupon">{{ $coupon->code }}</span><br>
<hr>
<span class="name">{{ $coupon->user->name }}</span>
</td>
#endforeach
</tr>
#endforeach
</table>
</div>
</div>
#endforeach
</div>

You can use the collection's chunk method to loop over chunks of your coupons:
<div class="coupons">
#foreach ($selectedCoupons->chunk(10) as $page)
<div class="page">
<div class="subpage">
<table>
#foreach ($page->chunk(2) as $row)
<tr>
#foreach ($row as $coupon)
<td>
<span class="coupon">{{ $coupon->code }}</span><br>
<hr>
<span class="name">{{ $coupon->user->name }}</span>
</td>
#endforeach
</tr>
#endforeach
</table>
</div>
</div>
#endforeach
</div>

Related

Get the the average of the data in laravel

I have two eloquent tables, vendor and work, in the work table there is a total score column and I want to get the average of the total score based on the vendor ID (foreign Key) and save it to the vendor table. May I know how to achieve this?
Here is my vendor table blade file
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Tabel Penilaian Penyedia</h3>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive">
<table id="tabelpenyedia" class="table table-bordered">
<thead>
<tr>
<th style="width: 10px">No.</th>
<th>Nama Penyedia</th>
<th>Nilai</th>
<th style="width: 120px">Aksi</th>
</tr>
</thead>
<tbody>
#php $no = 1; #endphp
#foreach ($penyedia as $penyedias)
<tr>
<td>{{$no++}}</td>
<td>{{$penyedias->nama}}</td>
<td></td>
<td>
Beri Penilaian
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</section>
Here is the AdminController
public function update_nilaipekerjaan(Request $request, $id){
$pekerjaan = Pekerjaan::find($id);
//$pekerjaan->update($request->all());
//$total = Pekerjaan::select(DB::raw('avg(nilai_1 + nilai_2 + nilai_3 + nilai_4) as nilai_total'))->get();
$pekerjaan->nilai_1=$request->nilai_1;
$pekerjaan->nilai_2=$request->nilai_2;
$pekerjaan->nilai_3=$request->nilai_3;
$pekerjaan->nilai_4=$request->nilai_4;
$pekerjaan->nilai_total=$request->nilai_1+$request->nilai_2+$request->nilai_3+$request->nilai_4;
$pekerjaan->update();
return redirect()->back()->with('message','Nilai Pekerjaan Berhasil diupdate!');
}
public function tabelnilai_penyedia(){
$penyedia = Penyedia::all();
$pekerjaan = Pekerjaan::all();
return view('admin.datanilai_penyedia', compact('penyedia', 'pekerjaan'));
} //I WANT TO SHOW THE AVERAGE OF THE TOTAL SCORE HERE.
Database https://imgur.com/a/N6NlcwJ
Here is what I want to achieve https://imgur.com/a/fk4Yq92
what I have tried
updating the AdminController
public function tabelnilai_penyedia($id){
$penyedia = Penyedia::all();
$pekerjaan = Pekerjaan::all();
$average = Pekerjaan::where('penyedia_id', $id)->avg('nilai_total');
Penyedia::where('id', $id)->update(['nilai'=>$average]);
return view('admin.datanilai_penyedia', compact('penyedia', 'pekerjaan'));
}
But it got me an error,
Too few arguments to function App\Http\Controllers\AdminController::tabelnilai_penyedia(), 0 passed in C:\Users\ASUS TUF\webpenyedia\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 1 expected
You can use the MySQL AVG function to get the average of a column, which in Eloquent is neatly wrapped in an aggregate function
Assuming your models are called "Work" and "Vendor"
// Get average of 'nilai' based on Vendor ID
$average = Work::where('penyedia_id', $vendorId) // Assuming this is the right column
->avg('nilai_total');
// Update Vendor directly in database (No model events)
Vendor::where('id', $vendorId)->update(['nilai' => $average]);

add rows and columns base on condition in laravel blade

I'm trying to create UI for cinema seats in laravel blade. i have seat_rows and seat_coulmns in my database and seat_rows will be the same for 2 rows. i mean first row is like this: id:1 seat_row:1 seat_column:1 and second row is like this: id:2 seat_row:1 seat:column:2. so i using bootstrap row and col classes and i wanna add row class only when number of seat_row changes. how can I DO that?
#foreach ($allseats as $seat)
{{-- #while ($seat->seat_row !== $seat->seat_row) --}}
<div id="{{$seat->seat_row}}" class="row ">
{{-- #for ($i = 1; $i <= 2; $i++) --}}
<div id="{{$seat->id}}" class="col-2 seats ">
<img src="{{asset('assets/img/seats/seat1.png')}}" alt="" style="height:50px;width:50px">
</div>
{{-- #endfor --}}
</div>
{{-- #endwhile --}}
{{$newrow=$seat->seat_row}}
#endforeach
you need to compare it with the previous seat.
Instead of using #foreach ($allseats as $seat) you can use #foreach ($allseats as $key => $seat)
and then check in your loop if $seat !== $allseats[$key-1]
I hope that guides you on the correct track.

Laravel Blade: If php code is wrapped with a display none, is it still run?

I'm trying to change the display fields from javascript. If a user selects from a drop down to show only in-stock items, I grab the id of the div and change the display from none to block. Is there any issue with it doing this way? Since the php code is not a query, I'm assuming it shouldn't be an issue if all the foreach statements get run and then their visibility controlled by the display on the div.
<div style="display:none" id = "no-filter">
#foreach ($collection->products('no-filter') as $product)
#include('prod-list')
#endforeach
</div>
<div style="display:none" id = "sale">
#foreach ($collection->products('sale') as $product)
#include('prod-list')
#endforeach
</div>
<div style="display:none" id = "in-stock">
#foreach ($collection->products('in-stock') as $product)
#include('prod-list')
#endforeach
</div>

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 show only one image in the index page in Laravel 5.6?

I have multiple images in my table witch related to vehicle_id, like this,
image table
id fileName vehicle_id
1 1.jpg 1
2 2.jpg 1
3 3.jpg 1
4 4.jpg 1
5 28.png 2
5 28.png 2
6 29.png 2
7 30.png 3
8 31.png 3
9 56.png 3
The vehicle table have way to many relationship with the image table and data grap using eager loader in VehicleController
$vehicles = Vehicle::with('image')->get();
return view('vechicles.index')->withVehicles($vehicles);
Now these images are showing in the vehicles/index.blade.php file
#foreach($vehicle->images as $image)
<tr>
<td><img src="/images/{{ $image->resized_name }}"></td>
</tr>
#endforeach
My problem is occurred now, in this way, I can show all images in the table which related to proper vehicle_id but, I need only show one image (to matching vehicle_id) like thumbnail to above line.
Then how can I configure this?
updated Controller
public function index()
{
$vehicles = Vehicle::with('images')->get();
return view('vechicles.index')->withVehicles($vehicles);
}
updated full blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
#if($vehicles)
#foreach($vehicles as $vehicle)
{{$vehicle->district}}
{{$vehicle->town}}
{{$vehicle->brand}}
{{$vehicle->model}}
<hr>
#foreach($vehicle->images as $image)
<tr>
<td><img src="/images/{{ $image->resized_name }}"></td>
</tr>
#endforeach
#endforeach
#endif
</div>
</div>
</div>
#endsection
You are looping through every images right now. You can simply retrieve an image using code below:
$vehicle->images()->first()->resized_name
So your code to display image will be:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
#if($vehicles)
#foreach($vehicles as $vehicle)
{{$vehicle->district}}
{{$vehicle->town}}
{{$vehicle->brand}}
{{$vehicle->model}}
<hr>
<tr>
<td>
<a href="{{route('vechicles.show',$vehicle->id)}}"><img
src="/images/{{ $vehicle->images()->first()->resized_name
}}"></a>
</td>
</tr>
#endforeach
#endif
</div>
</div>
</div>
#endsection
You can simply take only the first image. But be aware that you must verify if there are any images for that vehicle otherwise an exception will be thrown.
#if ($vehicle->images->isNotEmpty())
<a href="{{route('vechicles.show',$vehicle->id)}}">
<img src="/images/{{ $vehicle->images->first()->resized_name }}">
</a>
#endif
You can use limit along with with function like:
Vehicle::with(['image' => function($query) {
return $query->limit(1);
}])->get();
return view('vechicles.index')->withVehicles($vehicles);
And write code to show image as:
<tr>
<td><img src = "/images/{{ $vehicle->images[0]->resized_name }}"></td>
</tr>
You can use laravel first() function.
$vehicles = Vehicle::->where('vehicle_id', 1)->first();
You just have to dispaly the first array image in the blade as shown below:
#foreach ($vehicles as $v)
<img src = "/images/{{ $v->images[0]->resized_name }}"
#endforeach
(or) we can also use the laravel first() function to display the first record image from the collection
#foreach ($vehicles as $v)
<img src = "/images/{{ $v->images->first()->resized_name }}"
#endforeach

Categories