labas GamePage visogero labas GamePage visogero - 2 years ago 142
PHP Question

How to get subtotal when variable not in foreach loop ? Laravel

I'm developing a cart and I need to get a subtotal of items added to cart. How to do that when variable is outside of foreach loop ? At first I'm looping every product like this:

@foreach($products as $p)

And then how do I need to get the subtotal of all products price outside this loop ?

Sid Sid
Answer Source

There's not a clean solution for this if you want to achieve this in view however you can still use this code inside your view template as well.

You can pass the subtotal value explicitly from your controller method and display it in view. It could have been done like this. Add this code inside your controller function.

//initialize an empty array
$subtotal = [];
foreach($products as $p){
$price = $p['price'];
$title = $p['title'];
//push the price item to your subtotal array
array_push($subtotal, $price);

now you can use array_sum() to get the subtotal of your product like

$finalTotal = array_sum($subtotal);   //returns sum of an array

now i hope you are passing products from inside your controller. You just need to pass $finalTotal now. For example

return view('yourview')->with(array(
     'products'    => $products,
     'finalTotal' => $finalTotal 

Now in your blade template you can access subtotal by just doing {{$finalTotal}}. I hope you get it

You can embed this code in order to get total in view. I hope this will help you

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download