Wilson Guerrero
Wilson Guerrero

Reputation: 111

How to add values ​from a table in a LARAVEL resource

I would like to know if someone can help me, I do not know how I can add a total amount of items in my shopping cart, I need to count how many items (sum of quantities) the cart carries, every item in the cart have a value for quantity.

So far in my collection I have:

//this part is to get the data in the specific cart, I used to have ->where('cart_id', '=', $cart->id)->first() but of course just took the first value

 $cart = $request->route('cart');
    $data = DB::table('cart_items')
        ->where('cart_id', '=', $cart->id)
        ->get()->toArray();

//here it should makes a cycle and obtains and adds the quantity value for each item stored in that cart,

foreach ($data as $dat)
    $quant = $dat->quantity;
    $sum = 0;
    $total = $quant + $sum;

And $total should return a number with the whole add of quantities in the cart

 return [
        'Items' => $this->collection,
        'each_count' => $total,
    ];

the problem is that $total is returning 1, and not the sum of quantities.

Thank you in advance :)

Upvotes: 0

Views: 908

Answers (2)

Varsha Jadhav
Varsha Jadhav

Reputation: 91

As you want sum of quantities you can use basic function sum() $data->sum('$quantity');

Upvotes: 0

Chin Leung
Chin Leung

Reputation: 14941

Solution

You are only adding the quantity of your last item with 0, which gives you 1.

First of all, you have to wrap your loop with brackets.

foreach ($data as $dat) {
    // ...
}

Secondly, you then have to declare $total outside the loop so it does not get overwritten on each iteration.

$total = 0;

foreach ($data as $dat) {
    // ...
}

And lastly, update the total instead of assigning it inside your loop:

$total = 0;

foreach ($data as $dat) {
    $quantity = $dat->quantity;
    $sum = 0;
    $total += $quantity + $sum;
}

Not sure why your sum is hardcoded to zero though.


Method 2

If you only need the sum of the quantities, you can do $data->sum('quantity'); without looping through your items.

Upvotes: 2

Related Questions