Search code examples
phplaravellumenphp-closures

Value of $total not being set inside lumen collection map function


I have a lumen collection object for my order and use map function to iterate over it and do some logic. I also need the total value of the order which is calculated using quantity * price. But the variable that is responsible for holding the total value is always 0.

$total = 0;
$items = Cart_Item::where('user_id', $user->id)->get();
$items = $items->map(function ($item, $key) use ($order, $total) {
    $product = Product::where('id', $item->product_id)->first();
    $order_item = new Order_Item();
    $order_item->order_id = $order->id;
    $order_item->product_id = $item->product_id;
    $order_item->quantity = $item->quantity;
    $order_item->price = $product->GetPrice->price;
    $order_item->save();
    $total = $total + ($order_item->quantity * $order_item->price);
});

No matter what I do, the $total always returns 0.


Solution

  • The scope of your closure is not that of the entire file, but it's limited only to what's between the {} tags.

    The used variables are copied into the function scope.

    One solution would be to make $total a global variable:

    $total = 0;
    $items = Cart_Item::where('user_id', $user->id)->get();
    $items = $items->map(function ($item, $key) use ($order, $total) {
        $product = Product::where('id', $item->product_id)->first();
        $order_item = new Order_Item();
        $order_item->order_id = $order->id;
        $order_item->product_id = $item->product_id;
        $order_item->quantity = $item->quantity;
        $order_item->price = $product->GetPrice->price;
        $order_item->save();
    
        global $total;
        $total = $total + ($order_item->quantity * $order_item->price);
    });
    

    Another is to pass global as a reference &$total like so:

    $total = 0;
    $items = Cart_Item::where('user_id', $user->id)->get();
    $items = $items->map(function ($item, $key) use ($order, &$total) {
        $product = Product::where('id', $item->product_id)->first();
        $order_item = new Order_Item();
        $order_item->order_id = $order->id;
        $order_item->product_id = $item->product_id;
        $order_item->quantity = $item->quantity;
        $order_item->price = $product->GetPrice->price;
        $order_item->save();
    
        $total = $total + ($order_item->quantity * $order_item->price);
    });