how to loop through table in laravel calculate sum of a column - laravel

How do i calculate the totals of all values of a column amount after fetching it in laravel controller. table collections has only amount and id column and i want to determine the totals.

You can use sum from eloquent:
$amount = Collections::sum('amount');

You can do the following:
$total = 0;
$amounts = Collections::all()->pluck('amount');
foreach($amounts as $amount){
$total += $amount;
}

Related

Laravel: How to calculate sum of column values using eloquent?

I'm trying to use sum() get the sum of column value, but unfortunately it isn't working and I can't figure out where I am wrong.
$total = Invoice::where('status', 'Completed')
->sum('amount');
This returns error Call to a member function first() on string
invoices (Table)
id
code
status
amount
1
000001
Completed
300.00
2
000002
Completed
500.00
3
000003
Pending
100.00
I want to display the sum of invoices' amount in the view.
Blade View
Activity
Count
Total Amount
Invoices
6
900.00
try this:
$total = Invoice::select(
DB::raw(SUM(amount) as total_amount)
)->where('status', 'Completed')->pluck('total_amount');
and foreach the value in the view file like:
#foreach(total as total_value)
<td>{{total_value}}</td>
#endforeach
convert the `amount` attribute into Int before storing into database.for example
$amount = $request->amount;
$invoice = new Invoice();
$invoice->amount = (int)$amount;
--
--
--
$invoice->save();
then you can use the above query for column sum

Backpack for Laravel charts, append sum to chart

As I'm trying to implement charts into Backpack for Laravel, I been stuck for a few hours on this problem. The following script gets the number of users created for each day and appends them to an array that is then shown on the charts.
for ($days_backwards = 7; $days_backwards >= 0; $days_backwards--) {
// Could also be an array_push if using an array rather than a collection.
$users = Users::whereDate('created_at', today()->subDays($days_backwards))->count();
$user[] = $users;
}
Every iteration of the loop adds a number to the array (or is it a collection??) so something like [2,5,10,9,...].
I would rather like to get the total amount of users that ever registered, incrementally for each day, so that the result would be someting like [2,7,17,26,...].
I figured I could add each iteration with array_sum() but it's not working. Is it an array anyways? Is there a way to append to this list the sum to its previous?
Well I kind of figured out!
$sum = 0;
for ($days_backwards = 7; $days_backwards >= 0; $days_backwards--) {
$users = Users::whereDate('created_at', today()->subDays($days_backwards))->count();
$sum = $sum + $users;
$user[] = $sum;
}
It works!

foreach with get() return only one record laravel?

i want to sum profit by activating multiple plans. I am using get() with foreach but it returns only last row data. not all rows data. its strange while on other queries it returns all rows data.
for example, I have 2 deposits one 25$ and 2nd 35$ its returns 35$ data only.
i tried with
$deposits = Deposit::get();
but it is not working I went to increase rows to 12 but still, it returns data of 12th row only
$deposits = Deposit::where('account_id', $account->id)->where('status',1)->get();
foreach($deposits as $pn) {
$plans = package::where('id',$pn->plan)->first();
$percent = $plans->min_amount * $plans->percent/100;
}
After discussing in chat, the real problem is adding up the percentages during looping :
$percent = 0;
foreach ($deposited as $de) {
$pack = Package::Where('id', $de->plan)->first();
$log = Deposit::Where('id', $de->id)->first();
$percent = $percent + ($log->amount * $pack->percent / 100);
}

How to maintain total column in database

I'm new to laravel. I have one income table in the database and I want to maintain the total amount of users but there is a condition if the same user adds new deal_price then all the column will be updated except total and total will be updated like old deal_price+new deal_price.
this my controller
public function storeincome(Request $request){
$date=$request->get('date');
$parse_date=Carbon::parse($date)->format(' d-m-y H:i');
$party_name = $request->Input('party_name');
$deal_price = $request->Input('deal_price');
$mode = $request->Input('mode');
$slug = Str::slug($party_name, '');
$total = $request->Input('deal_price');
$data = array('date'=>$parse_date,'party_name'=>$party_name,'deal_price'=>$deal_price,'mode'=>$mode,'party_slug'=>$slug,'total'=>$total);
Income::insert($data);
return redirect(route('admin.dashboard'))->with('success', trans('message.success.create'));
}
this my table colums
Thanks.
Just update other columns normally and while updating the column 'total', fetch the value of deal_price(old) from your database and store it in a variable ($old_deal_price).
Now, just add the old_deal_price ($old_deal_price) and new_deal_price ($request->deal_price) and update that value in your 'total' field.
$total = ($old_deal_price) + ($request->deal_price);
Goodluck!

Using whereIn method to return multiple results for the same array value but at different index

$pidArray contains product ID's, some of those product ID's can be the same. I.E: 34 34 56 77 99 34. As is, it appears the whereIn method does not return results for a productId it has already found in $pidArray, even if it has a different index.
$productDataForOrder = Product::whereIn('id', $pidArray)->get(['id','price']);
$totalAmount = $productDataForOrder->sum('price');
$productDataForOrder now contains product data, but only for unique ProductID's in $pidarray. So when sum function is run, the sum is wrong as it does not take into account the price for multiple instances of the same productID.
The following code also does not return objects for every product ID in the array which are the same. So if $pidArray contains three identical product ID's, the query will only return a collection with one object, instead of three.
$query = Product::select();
foreach ($pidArray as $id)
{
$query->orWhere('id', '=', $id);
}
$productDataForOrder = $query->get(['id','price']);
$totalAmount = $productDataForOrder->sum('price');
You're not going to be able to get duplicate data the way that you're trying. SQL is returning the rows that match your where clause. It is not going to return duplicate rows just because your where clause has duplicate ids.
It may help to think of it this way:
select * from products where id in (1, 1)
is the same as
select * from products where (id = 1) or (id = 1)
There is only one record in the table that satisfies the condition, so that is all you're going to get.
You're going to have to do some extra processing in PHP to get your price. You can do something like:
// First, get the prices. Then, loop over the ids and total up the
// prices for each id.
// lists returns a Collection of key => value pairs.
// First parameter (price) is the value.
// Second parameter (id) is the key.
$prices = Product::whereIn('id', $pidArray)->lists('price', 'id');
// I used array_walk, but you could use a plain foreach instead.
// Or, if $pidArray is actually a Collection, you could use
// $pidArray->each(function ...)
$total = 0;
array_walk($pidArray, function($value) use (&$total, $prices) {
$total += $prices->get($value, 0);
});
echo $total;
The whereIn method only limits the results to the values in the given array. From the docs:
The whereIn method verifies that a given column's value is contained within the given array
Id make a query variable and loop through the array adding to the query variable in each pass. Something like this:
$query = Product::select();
foreach ($pidArray as $id)
{
$query->where('id', '=', $id);
}
$query->get(['id','price']);
Here is a code that would work for your use case expanding on #patricus
You first fetch an array of key as id and value as price from the products table
$prices = Product::whereIn('id', $pidArray)->lists('price', 'id');
$totalPrice = collect([$pidArray])->reduce(function($result, $id) use ($prices) {
return $result += $prices[$id];
}, 0);

Resources