App\Http\Controllers\OrdersController::addToOrderById PHP Method

addToOrderById() public method

Allows adding products to a specific order and create new wish lists.
public addToOrderById ( [type] $orderId, [type] $productId, Illuminate\Http\Request $request )
$orderId [type]
$productId [type]
$request Illuminate\Http\Request [laravel object]
    public function addToOrderById($orderId, $productId, Request $request)
    {
        $user = \Auth::user();
        $quantity = $request->get('quantity') ? $request->get('quantity') : 1;
        //checking whether the product required exist or not
        try {
            $product = Product::findOrFail($productId);
        } catch (ModelNotFoundException $e) {
            throw new NotFoundHttpException();
        }
        //checking whether the order required exist or not
        try {
            $order = Order::findOrFail($orderId);
        } catch (ModelNotFoundException $e) {
            throw new NotFoundHttpException();
        }
        if ($order) {
            //checking the order to make sure whether it needs an added product increase its quantity
            $orderDetail = OrderDetail::where('order_id', $order->id)->where('product_id', $product->id)->first();
            //if the product exists, its quantity is increased
            if ($orderDetail) {
                $orderDetail->price = $product->price;
                $orderDetail->quantity = $orderDetail->quantity + $quantity;
            } else {
                $orderDetail = new OrderDetail();
                $orderDetail->order_id = $order->id;
                $orderDetail->product_id = $product->id;
                $orderDetail->price = $product->price;
                $orderDetail->quantity = $quantity;
                $orderDetail->status = 1;
            }
            $orderDetail->save();
            $log = Log::create(['action_type_id' => '4', 'details' => $order->id, 'source_id' => $orderDetail->id, 'user_id' => $user->id]);
            Session::push('message', trans('store.productAddedToWishList') . ', ' . trans('globals.reference_label') . $order->description);
        } else {
            Session::push('messageClass', 'alert-danger');
            Session::push('message', trans('store.wishlist_no_exists') . ', ' . trans('globals.reference_label') . $order->description);
        }
        return redirect()->route('orders.show_wish_list_by_id', [$order->id]);
    }