How to sum up total in an index view in Laravel - php

I'm working on an invoice system in a homemade CRM. I try to sum up the price for all of my items to get the grand total.
I don't know how to get the grandtotal in my index view.
Here is my table in factures/show.blade.php
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Description</th>
<th class="text-right">Prix</th>
</tr>
</thead>
<tbody>
#foreach($facture->items as $item)
<tr>
<td>{{$item->description}}</td>
<td class="text-right">{{$item->prix}} $</td>
</tr>
#endforeach
<tr>
<td class="text-right">TPS</td>
<td class="text-right">{{ $item->calcultps() }} $</td>
</tr>
<tr>
<td class="text-right">TVQ</td>
<td class="text-right">{{ $item->calcultvq() }} $</td>
</tr>
<tr>
<td class="text-right">Total</td>
<td class="text-right">{{ $item->calculgrandtotal() }} $</td>
</tr>
</tbody>
</table>
and here is my table in factures/index.blade.php
<table class="table table-striped">
<thead><tr>
<th><p># de facture</p></th>
<th><p>Date</p></th>
<th><p>Description</p></th>
<th><p>Client</p></th>
<th class="text-right"><p>Montant</p></th>
<th class="text-right"><p>TPS</p></th>
<th class="text-right"><p>TVQ</p></th>
<th class="text-right"><p>Grand total</p></th>
</tr></thead>
#foreach($factures as $facture)
<tr>
<td>{{$facture->id}}</td>
<td>{{ $facture->created_at->format('d F Y') }}</td>
<td>{{ $facture->courtedescription}}</td>
<td>{{ $facture->client->prenom}} {{ $facture->client->nom}}</td>
<td class="text-right">{{ $facture->montant}} $</td>
<td class="text-right">{{ $facture->tps}} $</td>
<td class="text-right">{{ $facture->tvq}} $</td>
<td class="text-right"> IDONTKNOW $</td>
</tr>
#endforeach
</table>
here is my Item.php model
use Illuminate\Database\Eloquent\Collection;
class Item extends \Eloquent {
protected $fillable = ['nom', 'prix'];
public function facture()
{
return $this->belongsTo('Facture');
}
public function calcultps(){
$total = DB::table('items')->sum('prix');
$tps = $total *0.05;
echo $tps;
}
public function calcultvq(){
$total = DB::table('items')->sum('prix');
$tvq = $total *0.09975;
echo $tvq;
}
public function calculgrandtotal(){
$totalsanstaxes = DB::table('items')->sum('prix');
$tps = $totalsanstaxes *0.05;
$tvq = $totalsanstaxes *0.09975;
echo $totalsanstaxes+$tps+$tvq;
}
}
and my Facture.php model
use Illuminate\Database\Eloquent\Collection;
class Facture extends \Eloquent {
protected $fillable = [];
public function client()
{
return $this->belongsTo('Client');
}
public function items(){
return $this->hasMany('Item', 'facture_id');
}
}
my index function for my FacturesController.php
public function index()
{
$factures = Facture::all();
return View::make('factures.index')->withFactures($factures);
}
my show function for my FacturesController.php
public function show($id)
{
$facture = Facture::find($id);
return View::make('factures.show')->withFacture($facture);
}
I tried these (in the factures/index.blade.php) without success:
{{ $item->calculgrandtotal() }}
{{ $items->calculgrandtotal() }}
{{ $facture->items->calculgrandtotal() }}
and this returns an array
{{$facture->items}}
but this doesn't work
{{$facture->items->prix}}
I know there is something I don't understand here. and I wonder how to print out the grandtotal in my index view for each of the invoice?

I used the comment of #MattBurrow (thank you) and I managed to print out what I want using this:
index.blade.php
{{ Item::calculgrandtotal() }}
Item.php model
static function calculgrandtotal(){
$totalsanstaxes = DB::table('items')->sum('prix');
$tps = $totalsanstaxes *0.05;
$tvq = $totalsanstaxes *0.09975;
return $totalsanstaxes+$tps+$tvq;
}

Related

How do i calculate and view total work_time for specific id in laravel?

I have two tables employes and attendances . What I want is to sum work_time for each employe id and show in my view.
employes Table
id
attendances Table
id
employe_id
work_time
I want to sum work_time column for specific employe id. I am new to laravel so how do I do that with laravel eloquent.
Employe.php
class Employe extends Model{
use HasFactory;
protected $fillable=['id','employe_code','employe_name','workplace'];
public function employee(){return $this->hasMany(Attendance::class);}}
Attendance.php
class Attendance extends Model{use HasFactory;
protected$fillable['id','employe_id','attendence_date','clock_in','clock_out','work_time','attendence_status'];
public function employe()
{return $this->belongsTo('App\Models\employe', 'employe_id');}}
AttendanceController
public function attendance(){
$attendances = Employe::all();
$hour = Attendance::where('employe_id',1)->sum('work_time');
return view('pages.Attendance.hour', compact('attendances','hour')); }
hour.blade.php
```
<table id="datatable" class="table table-hover table-sm table-bordered p-0" data-page-length="50"
style="text-align: center">
<thead>
<tr>
<th class="alert-success">#</th>
<th class="alert-success">employe_code</th>
<th class="alert-success">employe_name</th>
<th class="alert-success">work_time</th>
</thead>
<tbody>
#foreach($attendances as $attendances)
<tr>
<td></td>
<td>{{ $attendances->employe_code }}</td>
<td>{{ $attendances->employe_name }}</td>
<td>Hour {{ $hour }} </td>
</tr>
#endforeach
</table>
Only for Laravel 8.12 and above, you can use withSum()
First of all, correct the relation name in Employe.php
class Employe extends Model{
use HasFactory;
protected $fillable=['id','employe_code','employe_name','workplace'];
public function attendances(){ //<---- here
return $this->hasMany(Attendance::class);
}
}
Here is the controller
public function attendance(){
$attendances = Employe::query()->withSum('attendances', 'work_time')->get();
return view('pages.Attendance.hour', compact('attendances'));
}
And the blade (kept the variable name $attendances but you should change it to employees)
<table id="datatable" class="table table-hover table-sm table-bordered p-0" data-page-length="50" style="text-align: center">
<thead>
<tr>
<th class="alert-success">#</th>
<th class="alert-success">employe_code</th>
<th class="alert-success">employe_name</th>
<th class="alert-success">work_time</th>
</thead>
<tbody>
#foreach($attendances as $employe)
<tr>
<td></td>
<td>{{ $employe->employe_code }}</td>
<td>{{ $employe->employe_name }}</td>
<td>Hour {{ $employe->attendances_sum_work_time }} </td>
</tr>
#endforeach
</table>

Laravel - Counting a collection of models

I'm trying to get the count of different models and list them by company.
I have a collection of different models.
public function listAllRequets()
{
$requests = collect();
$terms = Termination::with('user.company')->where('default_status', 2)->get();
$deacs = LoaDeactivation::with('user.company')->where('manager_status', 2)->get();
$reacs = LoaReactivation::with('user.company')->where('manager_status', 2)->get();
// Use push() to collect them all in one collection
foreach ($terms as $term)
$requests->push($term);
foreach ($deacs as $deac)
$requests->push($deac);
foreach ($reacs as $reac)
$requests->push($reac);
return $requests;
}
In my index function I'm adding them to $requests.
To get the list of companies I'm grouping them using the groupBy() method.
public function index()
{
$requests = $this->listAllRequets();
$requestCompanies = $requests->groupBy(function($requests) {
return $requests->user->company->company_acronym;
});
In my view I have this:
<table class="table table-sm">
<thead class="thead-light">
<tr>
<th>Company</th>
<th class="text-center">Terms</th>
<th class="text-center">Deacs</th>
<th class="text-center">Reacs</th>
</tr>
</thead>
<tbody>
#foreach ($requestCompanies as $company => $requests)
<tr>
<td class="pt-3"><strong>{{ $company }}</strong></td>
#foreach ($requests as $request)
<td class="text-center">{{ $request-> }}</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>
I need a way to get the count of each model by company.
My companies list out as expected but I'm not sure how to get the correct model count.
If you have relationships among your company and each request model (Termination, LoaDeactivation, LoaReactivation), wouldn't be easier to do that with a query at database level?
That seems a nice use case for with count method that eloquent provides:
Assuming the relations in the company model are called terminations, deactivations and reactivations, you could do:
public function index()
{
$companies = Company::withCount('terminations','deactivations','reactivations')->get();
// here pass $companies array to your view
}
Then in your view you can access the count for each type on each company:
<table class="table table-sm">
<thead class="thead-light">
<tr>
<th>Company</th>
<th class="text-center">Terms</th>
<th class="text-center">Deacs</th>
<th class="text-center">Reacs</th>
</tr>
</thead>
<tbody>
#foreach ($companies as $company)
<tr>
<td class="pt-3"><strong>{{ $company->name }}</strong></td>
<td class="text-center">{{ $company->terminations_count }}</td>
<td class="text-center">{{ $company->deactivations_count }}</td>
<td class="text-center">{{ $company->reactivations_count }}</td>
</tr>
#endforeach
</tbody>
</table>

print readable message for tiny int value

I have a column PAID tinyint(1). Now I want to display this value 0/1 as UNPAID/PAID in view page table. How should I do this?
Also if the PAID column data is PAID then color it as green and if UNPAID then color it as BLUE. How can I do this?
controller code block to fetch data
function fetchData() {
$ordered_books = OrderedBook::orderBy('id', 'DESC')->get()->toArray();
return compact('ordered_books');
}
view page table code block
<table id="showBooksIn" class="table table-bordered gridview">
<thead>
<tr>
<th>BOOK ID</th>
<th>BILLED DATE</th>
<th>BILLED NUMBER</th>
<th>QUANTITY</th>
<th>PRICE</th>
<th>PAID</th>
<th>REMARKS</th>
</tr>
</thead>
<tbody>
#foreach($ordered_books as $data)
<tr>
<td> {{$data['BookID']}} </td>
<td> {{$data['BilledDate']}} </td>
<td> {{$data['BilledNum']}} </td>
<td> {{$data['Qunatity']}} </td>
<td> {{$data['Price']}} </td>
<td> {{$data->bill_paid}} </td>
<td> {{$data['Remarks']}} </td>
</tr>
#endforeach
</tbody>
</table>
As suggested I edited my model class
class OrderedBook extends Model
{
//
protected $appends = ['bill_paid'];
public function getBillPaidAttribute(){
if($this->BillPaid == 0){
return 'UNPAID';
}else {
return 'PAID';
}
}
}
Now getting error as :: ErrorException (E_NOTICE) Undefined property: App\OrderedBook::$BillPaid
Use if conditions in your blade template and apply css for coloring.
#foreach($ordered_books as $data)
<tr>
<td> {{$data['BookID']}} </td>
<td> {{$data['BilledDate']}} </td>
<td> {{$data['BilledNum']}} </td>
<td> {{$data['Qunatity']}} </td>
<td> {{$data['Price']}} </td>
#if($data['BillPaid'] === 0)
<td style='color:blue;'> UNPAID </td>
#else
<td style='color:green;'> PAID </td>
#endif
<td> {{$data['Remarks']}} </td>
</tr>
#endforeach
make Eloquent: Mutators in OrderBook
protected $appends = ['bill_status']
public function getBillStatusAttribute(){
if($this->BillPaid == 0){
return 'unpaid';
}else {
return 'paid';
}
}
in view
$orderBook->bill_status

How can I rearrange this table to another away laravel eloquent relation

I used laravel hasmany relationship in my user model. I just want to convert my table like below (row to column):
To:
Here is my User model:
public function meal(){
return $this->hasMany(Meal::class);
}
My controller:
public function index()
{
$members = User::all();
return view('admin.meal')->with([
'members' => $members,
]);
}
and #blade
<table class="table table-striped #if(count($members)>7) table-responsive #endif ">
<thead>
<tr class="text-uppercase">
{{--<th class="font-w700">Date</th>--}}
#foreach($members as $member)
<th class="font-w700">{{str_limit($member->fname,5,'...')}}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach($members as $member)
<tr>
#foreach($member->meal as $meal)
<td><span class="font-w600">{{$meal->user_id}}</span></td>
#endforeach
</tr>
#endforeach
</tbody>
</table>

Trying to get property of non-object Laravel 5.4

Hi Guy's Im always getting an error from laravel 5.4.
Im creating a list of members... but when i use #foreach it says
ErrorException in 6163a8b030c7474bc8eaad359ab99eb61ebdb127.php line 38:
Trying to get property of non-object (View: E:\wamp64\www\gplspring2017\resources\views\admin\memberlist.blade.php)
Here's my controller
public function listmember(Request $request, $idteam)
{
$teams = DB::table('gpl_team')->where('gpl_team_id', $idteam)->first();
$count = count($teams);
if (!$count) {
return redirect('404');
} else {
return view('/admin/memberlist', ['team' => $teams]);
}
}
and here's my view code:
<table class="table table-striped">
<tr>
<td style="width:15%;"></td>
<td style="width:25%;">Summoners Name</td>
<td style="width:25%;">Name</td>
<td style="width:25%;">Role</td>
<td style="width:10%;"></td>
</tr>
<?php
$qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();
$counting = count($qmember);
?>
#if (! $counting)
<tr>
<td colspan="4"> No Recored! </td>
</tr>
#else
#foreach($qmember as $get_member)
<tr>
<td><img src="{{ $get_member->member_pic }}" /></td>
<td></td>
<td></td>
<td></td>
<td>
<div class="glyphicon glyphicon-pencil"></div> |
<div class="glyphicon glyphicon-trash"></div>
</td>
</tr>
#endforeach
#endif
</table>
When i remove the foreach the code is working.. but i try to add the #foreach($qmember as $get_member) it not working anymore...
Check this line:
$qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();
when you are using first() then it does not return an Std Class object. If you want it so then use get()
Using first() method you are fetching only one record from DB that match with the ID (First one matched). You need to use get().
Controller:
public function listmember(Request $request, $idteam)
{
$teams = DB::table('gpl_team')->where('gpl_team_id', $idteam)->get(); //Use get() if you expect more than one result not first()
$count = count($teams);
if(! $count)
{
return redirect('404');
}
else
{
return view('/admin/memberlist', ['teams' => $teams]);// this team variable must be used in the blade
}
}
View:
<table class="table table-striped">
<tr>
<td style="width:15%;"></td>
<td style="width:25%;">Summoners Name</td>
<td style="width:25%;">Name</td>
<td style="width:25%;">Role</td>
<td style="width:10%;"></td>
</tr>
<?php
$qmember = DB::table('team_member')->where('gpl_team_id', $team->gpl_team_id)->first();
$counting = count($qmember);
?>
#if (! $counting)
<tr>
<td colspan="4"> No Recored! </td>
</tr>
#else
#foreach($teams as $team)
<tr>
<td><img src="{{ $team['member_pic'] }}" /></td>
<td></td>
<td></td>
<td></td>
<td>
<div class="glyphicon glyphicon-pencil"></div> |
<div class="glyphicon glyphicon-trash"></div>
</td>
</tr>
#endforeach
#endif
</table>

Categories