killerbeast2017's avatar

Performing Arithmetic Operations inside Laravel Controller

I am writing an APIs in Laravel for an ecommerce site. I need to pass on data as JSON. I can pass the list of all items in the user's cart. I also need to pass the total amount as a separate object in my JSON. The below is my code that doesn't work:

    $items = Cart_Item::where('user_id', $user->id);
    $total = 0;
    $items = $items->map(function ($item, $key) {
        $product = Product::where('id', $item->product_id)->first();
        $total = $total + $item->quantity * $product->GetPrice->price;
        return [
            'id'    => $item->id,
            'product_id' => $item->product_id,
            'quantity' => $item->quantity,
            'name'  => $product->name,
            'price' => $product->GetPrice->price,
        ];
    });

    return response()->json([
        'data' => $items,
        'total' => $total
    ], 200);

As you can see I can't perform arithmetic operations on my controller. Why is that? What can I do to make it work?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

What is probably happening is you are not passing the $total variable into the closure

$items = $items->map(function ($item, $key) use ($total) {
    // ...
});
3 likes

Please or to participate in this conversation.