How to get total amount from foreach lop in Laravel Controller - laravel

I want to get total amount from foreach lop data in the controller, for example, code bellow.
$set = settings::findOrFail(1);
$api = new \Binance\API("$set->api_key","$set->scrt_key");
$api->useServerTime();
$forusdvaluetotal = coins::whereuser_id(Auth::user()->id)->get();
foreach($forusdvaluetotal as $coins){
$getsymbol = $coins->symbol.'USDT';
$getprice = $api->price("$getsymbol");
$valueinusd = $coins->balance*$getprice;
$total = $valueinusd;
}
$gettotal = $total->sum();
like "coins A" price is $50 per coin and balance 2, "coins B" price is $50 per coin and balance 5, "coins C" price is $50 per coin and balance 1. So I want to get total amount in USD by balance like ('coins A' $502 = $100 + 'coins B' $505 = $250 + 'coins A' $50*1 = $50) = $400
Please help me how to solve that in laravel controller.

Try this:
$total = 0;
foreach($forusdvaluetotal as $coins){
$getprice = $coins['market_price'];
$valueinusd = $coins['balance']*$getprice;
$total += $valueinusd;
}
return $total;

One elegant option would be to make use of Laravel's support collection method reduce().
The reduce method reduces the collection to a single value, passing
the result of each iteration into the subsequent iteration:
The value for $carry on the first iteration is null; however, you
may specify its initial value by passing a second argument to
reduce:
$collection = coins::whereuser_id(Auth::user()->id)->get();
$total = $collection->reduce(function ($carry, $item) {
return $carry + (floatval($item->balance) * floatval($item->market_price));
}, 0);
Addendum
Alternatively, you may make use of Laravel's support collection method sum().
The sum method returns the sum of all items in the collection:
In addition, you may pass your own closure to determine which values
of the collection to sum:
$collection = coins::whereuser_id(Auth::user()->id)->get();
$total = $collection->sum(function ($item) {
return (floatval($item->balance) * floatval($item->market_price));
});
Edit:
In response to your new question changes, you could solve it this way.
$set = settings::findOrFail(1);
$api = new \Binance\API("$set->api_key","$set->scrt_key");
$api->useServerTime();
$query = coins::whereuser_id(Auth::user()->id);
// Get symbols.
$symbols = (clone $query)->distinct('symbol')->pluck('symbol')->flip()->toArray();
// Fetch prices.
array_walk($symbols, function (&$value, $key) use ($api) {
$value = $api->price("{$key}USDT");
});
// Get total sum.
$total = $query->get()->reduce(function ($carry, $item) use ($symbols) {
return $carry + (floatval($item->balance) * floatval($symbols[$item->symbol]));
}, 0);

Related

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);
}

Laravel 5 - how to get a random row from first 30 records in eloquent?

I am trying to get a random row from the top 30 records in a table. I sort all the records by score first, and take 30 records in a scope of the eloquent model:
public function scopePopular($query, $d)
{
return $query->where('d', $d)->orderBy('score', 'desc')->take(30);
}
Then in a class:
$cnt = Record::popular($d)->count();
if ($cnt == 0)
return;
$randIndex = rand(0, $cnt-1);
$record = Record::popular($d)->skip($randIndex)->take(1)->first();
return $record;
But when I check in php artisan tinker, I found that Record::popular($d)->count(); will return all the records number instead of 30. How can I correct this problem? Thanks.
Use get() before count() to run the query before count:
$cnt = Record::popular($d)->get()->count();
You are running the query 2 times. That is not necessary.
$cnt = Record::popular($d)->count(); // First query
if ($cnt == 0)
return;
$randIndex = rand(0, $cnt-1);
$record = Record::popular($d)->skip($randIndex)->take(1)->first(); // Second query
return $record;
Instead you can do it like this:
return Record::popular($d)->get()->random(); // One query only

Make unique invoice numbers with mysql and use

At the moment this is my function to create a random unique invoice number which is stored in a form's hidden field
function generate_invoice_number() {
global $wpdb;
$lastVisitor = $wpdb->get_results("SELECT visitorID FROM event_visitors_2014 ORDER BY visitorsID DESC LIMIT 1", ARRAY_A);
$nr_last = $lastVisitor[0]['visitorID'];
$nr = 501 + $nr_last;
$value = sprintf( '%04d', $nr );
$number = 'LEDEXPO'.date('Y').'-'.uniqid().'-'.$value;
return $number;
}
I have a problem when multiple people are using the form at the same time, say 3 people are using the form they all have the same number generate.
So i added uniqid(), so $value could be duplicated but $number should be unique? Is this correct or is there a better way?
How can i make test function to test this function on uniqueness?
regards
Try This:
function generate_invoice_number()
{
global $wpdb;
$lastVisitor = $wpdb->get_results("SELECT visitorID FROM event_visitors_2014 ORDER BY visitorsID DESC LIMIT 1", ARRAY_A);
$nr_last = $lastVisitor[0]['visitorID'] + 1;
$number = date('Ymd') . $nr_last;
return $number;
}

how to count items in an order(when item status=Mixed) using orderid in magento?

I am trying to count total number of items in an order but I am unable to do so correctly.
I am using this code -
$total=0;
$order = Mage::getModel('sales/order')->load($oid);
$items = $order->getAllItems();
foreach($items as $item){
$qty = $item->getQtyToInvoice();
$total = $total + $qty;
}
echo "total :".$total;
This print correct result if the items status in orders is shipped but if the item status is mixed ,it prints 0 .
Are you simply looking for the number of items ordered, regardless of its shipped/invoiced/refunded status?
If so then then replace getQtyToInvoice() with getQtyOrdered().
For example:
foreach($items as $item){
$qty = $item->getQtyOrdered();
}
To answer the question in the comments: "I am also looking for the number of items shipped"
$item->getQtyShipped()

Resources