Tuesday, February 28, 2017

Order object not defined inside collection's map function

I have 2 tables for placing my order. In my orders table I contain the main details for the order and in my order_item table, I have the details of each item that was ordered. This is my code for the same:

    $order = new Order();
    $order->user_id = $user->id;
    if(!$order->save()){
        return response()->json([
            'message' => 'Unable to place your order. Try again.'
        ], 500);
    }

    $items = Cart_Item::where('user_id', $user->id)->get();
    if($items->isEmpty()){
        return response()->json([
            'message' => 'Kindly add items to the cart before placing an order.'
        ], 500);
    }
    $items = $items->map(function ($item, $key) {
        $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;
        if(!$order_item->save()){
            return response()->json([
                'message' => 'Unable to place your order. Try again.'
            ], 500);
        }
    });

When I try to execute this, I get this error Undefined variable: order on the line $order_item->order_id = $order->id;. Why can't I access the order object?




via JackSlayer94

Advertisement