Nested Loop in Eloquent in Laravel - php

I am having trouble with my code. I have two tables Stocks and StockLists however, I want to get all the related stock in the stocks list based on the stock code. But the result is repeated in each stocks....
Here is the link of the image https://www.screencast.com/t/rHdT2gigh
public function index()
{
$stocks = Stock::all();
foreach ($stocks as $stock) {
$stockInfos = DB::table('stocksList')
->where('stockCode', $stock->stockCode)
->take(3)
->get();
}
return view('welcome', compact('stocks', 'stockInfos'));
}
Here is my blade.php
#forelse($stocks as $stock)
<tr align="left">
<th scope="row">{{ $stock->stockCode }}</th>
<td><strong>{{ $stock->stockName }}</strong></td>
<td><strong>
#forelse($stockInfos as $stockInfo)
{{ $stockInfo->stockDate }} : {{ $stockInfo->stockPrice }}
<br>
#empty
<em>No Data</em>
#endforelse
</strong></td>
</tr>
#empty
#endforelse

You are overwritting the $stockInfos variable try with
public function index()
{
$stocks = Stock::all();
$stockInfos = [];
foreach ($stocks as $stock) {
array_push($stockInfos,DB::table('stocksList')
->where('stockCode', $stock->stockCode)
->take(3)
->get());
}
return view('welcome', compact('stocks'))->with('stockInfos',collect($stockInfos));
}
And in your view :
#forelse($stocks as $stock)
<tr align="left">
<th scope="row">{{ $stock->stockCode }}</th>
<td><strong>{{ $stock->stockName }}</strong></td>
<td><strong>
#forelse($stockInfos->where('stockCode',$stock->stockCode) as $stockInfo)
{{ $stockInfo->stockDate }} : {{ $stockInfo->stockPrice }}
<br>
#empty
<em>No Data</em>
#endforelse
</strong></td>
</tr>
#empty
#endforelse

Try this :
$stockInfos = DB::table('Stock')
->join('stocksList','stocksList.stockCode','=','Stock.stockCode')
->get();

Related

How can i add two numbers in foreach blade in laravel and display the total

I need to add two numbers passed by the foreach in the blade view
how can i add this two numbers instead of showing it as individual 333.34 333.34,
I need to show it as 666.68 / 1000 AUD
Here's how blade foreach looks like
#if(!empty($teams)&&count($teams)>0)
#foreach($teams as $key=>$team)
<table>
<tr>
<th>id</th>
<th>Team Name</th>
<th>Payment</th>
<th>Time Remaining</th>
<th>Num of Players Paid</th>
<th>Paid out of</th>
<th>Captain Name</th>
<th>Status</th>
</tr>
<tr>
<td>{{$key+1}}</td>
<td>{{$team->name}}</td>
<td>{{($team->pivot->status==0)?'PENDING':(($team->status==1)?'REGISTERED':(($team->pivot->status==3)?'REMOVED':(($team->pivot->status==2)?'WITHDRAWN':'')))}}</td>
<td>
#if ($team->pivot->status == 0)
{{\Carbon\Carbon::createFromTimeStamp(strtotime($team->pivot->created_at.' +1 day'))->diffForHumans(null, true, true, 2)}}
#else
Registered at {{$team->pivot->updated_at->todatestring()}}
#endif
</td>
<td>{{ $team->competitionPayments->count() . '/' . $team->players->count() .' PAID'}}</td>
<td>
#foreach ($team->competitionPayments as $amount)
{{ $amount->amount }}
#endforeach
/
#foreach ($team->competitions as $total)
{{ $total->pivot->total_fee .' AUD'}}
#endforeach
</td>
<td>{{$team->captain->full_name}}</td>
<td>{{$team->pivot->status}}</td>
{{-- <td>{{($team->pivot->status==0)?'PENDING':(($team->status==1)?'REGISTERED':(($team->pivot->status==3)?'REMOVED':(($team->pivot->status==2)?'WITHDRAWN':'')))}}</td> --}}
</tr>
</table>
<table>
<tr>
<th>Full Name</th>
<th>DOB</th>
<th>Active Kids Voucher AKV</th>
<th>Accept Reject AKV</th>
<th>Paid $</th>
<th>Paid By </th>
<th>Total</th>
<th>Stripe</th>
<th>Mobile</th>
<th>Email</th>
<th>T&C</th>
</tr>
#foreach ($team->players as $player)
<tr>
<td>{{ $player->full_name }}</td>
<td>{{ $player->dob }}</td>
<td>-</td>
<td>-</td>
<td>
{!! $player->competitionPayments->isNotEmpty() ?
implode($player->competitionPayments->map(function($item, $key) {
return ($key > 0 ? '<div class="mb-1"></div>' : '') . number_format($item->amount, 2) . ' AUD <br> <hr>' . $item->updated_at->todatestring();
})->toArray()) : '-' !!}
</td>
<td>{{ $player->competitionPayments->isNotEmpty() ? $player->competitionPayments->implode('paidBy.name') : '-' }}</td>
<td>-</td>
<td>-</td>
<td>{{ $player->mobile }}</td>
<td>{{ $player->email }}</td>
<td>-</td>
</tr>
#endforeach
</table>
<br><br><hr><br><br>
#endforeach
#else
<tr>
<td colspan="6">
<div class="text-muted small text-center">
No teams have registered yet
</div>
</td>
</tr>
#endif
Heres the relationship in my Team model
public function competitionPayments()
{
return $this->hasMany(CompetitionPayment::class, 'team_id');
}
Here's my controller function
public function detailedRegistrations($competition)
{
$competitions = $this->competitionsRepo->findOrFail($competition);
$teams = $competitions->teams()->get();
$payments = $competitions->payments()->get();
return view('competitions.detailed-registrations',
[
'teams'=>$teams,
'payments'=>$payments,
'competitions'=>$competitions,
]
);
}
I tried to add the sum() and get the total as below and i got a wrong total and repeated
<td>
#foreach ($team->competitionPayments as $amount)
{{ $amount->sum('amount') }}
#endforeach
/
#foreach ($team->competitions as $total)
{{ $total->pivot->total_fee .' AUD'}}
#endforeach
</td>
This is the total i got
Someone please help me out or suggest a way that i could fix this issue
Thank You
Try array_sum() method. Replace this block
#foreach ($team->competitionPayments as $amount)
{{ $amount->amount }}
#endforeach
With this
#php
$temparr = (array) $team->competitionPayments
#endphp
{{array_sum(array_column($temparr,'amount'))}}
Or directly try
#php
$sum = 0
#endphp
#foreach ($team->competitionPayments as $amount)
$sum = $sum + $amount->amount
#endforeach

Laravel view foreach with two properties

i need help with my foreach loop in view
Controller.php
$expenses = Expense::groupBy('category_id')->selectRaw('sum(amount) as sum, category_id')->pluck('sum','category_id');
$categories = Category::all();
return view('dashboard.index', compact('expenses','categories'));
index.php
<table class="table">
<thead>
<th>Category</th>
<th>Expenses</th>
</thead>
<tbody>
#foreach($categories as $category)
<tr>
<td>{{ $category->name }}</td>
#foreach($expenses as $expense)
<td>{{ $expense }}</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>
I get the output like this.
enter image description here
It outputs the expense 2 times, is there a limiter for "foreach loop" or is there another way on doing this?
You need to add a condition for that $category->id is the same as category_id
#foreach($expenses as $key => $expense)
#if($key == $category->id)
<td>{{ $expense }}</td>
#endif
#endforeach
The right way to do it is by using join or relationship.
$expenses = Expense::join('categories','categories.category_id','expenses.category_id')->groupBy('expenses.category_id')->selectRaw('sum(expenses.amount) as sum, expenses.category_id','categories.name')->get();
<table class="table">
<thead>
<th>Category</th>
<th>Expenses</th>
</thead>
<tbody>
#foreach($expenses as $expense)
<th>{{ $expense->name }}</th>
<td>{{ $expense->sum }}</td>
#endforeach
</tbody>
</table>
You should limit the results in controller, but here's how you can accomplish this in a blade. Not pretty
#foreach ($element['subs'] as $item)
#if($loop->index < 10)
// Your code
#endif
#endforeach
You should compare category_id with category->id.
#foreach($categories as $category)
<tr>
<td>{{ $category->name }}</td>
#foreach($expenses as $expense)
#if($expense->category_id == $category->id )
<td>{{ $expense->sum }}</td>
#endif
#endforeach
</tr>
#endforeach

Pagination in laravel returning method undefined

The pagination method returns App\Article::link undefined, any ideas? I thought this was a helper method
public function index()
{
$data = Article::paginate(5);
return view('datatypes.articles.index', compact('data'));
}
in my view:
<tbody>
#foreach($data as $data)
<tr>
<th scope="row">{{$data->id}}</th>
<td>{{$data->title}}</td>
</tr>
#endforeach
</tbody>
{{ $data->links() }}
<tbody>
#foreach($data as $_data)
<tr>
<th scope="row">{{$_data->id}}</th>
<td>{{$_data->title}}</td>
</tr>
#endforeach
</tbody>
{{ $_data->links() }}
try this in your view
<tbody>
#foreach($data as $item)
<tr>
<th scope="row">{{$item->id}}</th>
<td>{{$item->title}}</td>
</tr>
#endforeach
</tbody>
{{ $data->links() }}

How to display count result to blade template

I have attendance table then I perform count to total all the Present(P)Absent(A)Late(L) now how can I show it to blade template inside the html input with 3 separated value example: value=P, value=A, value=L;
right now with my code I'm getting it as all
controller:
public function get_status(){
$from = date('2018-01-01');
$to = date('2018-03-31');
$atnds = DB::table('attendances')
->select(DB::raw('count(*) as total, status'))
->where('status', '<>', 'status')
->whereBetween('days', [$from,$to])
->groupBy('status')
->where('lead_id', '=', 1)
->get();
return view('total',compact('atnds'));}
DD RESULT
[{"total":7,"status":"A"},{"total":9,"status":"L"},{"total":65,"status":"P"}]
If you want with input then you can use it like this
<table style="width:100%">
<tr><th>Status </th> <th>Total</th></tr>
#foreach($atnds as $at)
<tr>
<td>{{ $at->status }}</td>
<td><input type="text" value ="{{ $at->total }}" /></td>
</tr>
#endforeach
</table>
In blade you could use
<table style="width:100%">
#foreach($atnds as $ad)
<tr>
<td>{{ $ad->total }}</td>
<td>{{ $ad->status }}</td>
</tr>
#endforeach
</table>
If you want to break them out i would do so before returning it to the blade
$status = []
foreach($atnds as $ad) {
$status[$ad->status] => $ad->total
}
$status = collect($status);
return view('total',compact('status'));
and in the blade you should now be able to do
{{ $status->L }}
or
{{ $status['L'] }}

Laravel 5.4 - controller logic to show the status of a blog post on view

new to Laravel, and just having this problem that I couldn't figure it out.
I have a post controller set up to query out all blog posts. On the database, I have a integer column and named as "status", 0 as inactive, 1 as active. The question is how and where to place the logic to check whetherthe status is 0 or 1, and show "inactive" or "active" in the view. Thanks in advance.
public function index()
{
$posts = Post::where('user_id', 1)->orderBy('id', 'desc')->paginate(5);
return view('post.index')->withPosts($posts);
}
Here is the view
<table class="table">
<tr>
<th>Date Created</th>
<th>Title</th>
<th>Status</th>
</tr>
#foreach ($posts as $post)
<tr>
<td>{{datePretty($post->created_at) }}</td>
<td>{{ $post->title }}</td>
<td></td>
</tr>
<br>
#endforeach
</table>
you can have that logic inside your blade template:
#foreach ($posts as $post)
<tr>
<td>{{datePretty($post->created_at) }}</td>
<td>{{ $post->title }}</td>
<td>#if($post->status) active #else inactive #endif</td>
</tr>
<br>
#endforeach

Categories