Laravel form action not accepting $order->id but accepting hard coded value

68 Views Asked by At

I debugged the code using {{ dd($order->id) }} and received the order id value of 100238. However, when I used the following:

<form action="{{ route('admin.pos.update_order', ['id' => $order->id]) }}" method="post">

It did not work. When I replaced $order->id with the actual id value like this: {{ route('admin.pos.update_order', ['id' => 100238]) }}, it worked perfectly.

I'm unable to resolve this abnormal behavior. Despite the fact that debugging provides the order id, it doesn't seem to work in the action code as $order->id. Can anyone guide me on what the actual issue might be?

Route

Route::group(['middleware' => ['admin']], function () {
    Route::group(['prefix' => 'pos', 'as' => 'pos.', 'middleware' => ['module:pos_management']], function () {
        Route::post('update_order/{id}', 'POSController@update_order')->name('update_order');
    });
});

Update Order Controller

public function update_order(Request $request, $id): RedirectResponse
    {
        $order = $this->order->find($order_id);
    
        if (!$order) {
            Toastr::error(translate('Order not found'));
            return back();
        }
    
        $order_type = $order->order_type;
    
        if ($order_type == 'delivery') {
            Toastr::error(translate('Cannot update delivery orders'));
            return back();
        }
    
        $delivery_charge = 0;
    
        if ($order_type == 'home_delivery') {
            if (!session()->has('address')) {
                Toastr::error(translate('Please select a delivery address'));
                return back();
            }
    
            $address_data = session()->get('address');
            $distance = $address_data['distance'] ?? 0;
            $delivery_type = Helpers::get_business_settings('delivery_management');
            
            if ($delivery_type['status'] == 1) {
                $delivery_charge = Helpers::get_delivery_charge($distance);
            } else {
                $delivery_charge = Helpers::get_business_settings('delivery_charge');
            }
    
            $address = [
                'address_type' => 'Home',
                'contact_person_name' => $address_data['contact_person_name'],
                'contact_person_number' => $address_data['contact_person_number'],
                'address' => $address_data['address'],
                'floor' => $address_data['floor'],
                'road' => $address_data['road'],
                'house' => $address_data['house'],
                'longitude' => (string)$address_data['longitude'],
                'latitude' => (string)$address_data['latitude'],
                'user_id' => $order->user_id,
                'is_guest' => 0,
            ];
            
            $customer_address = CustomerAddress::create($address);
        }
    
        // Update order details
        $order->coupon_discount_title = $request->coupon_discount_title == 0 ? null : 'coupon_discount_title';
        $order->coupon_code = $request->coupon_code ?? null;
        $order->payment_method = $request->type;
        $order->transaction_reference = $request->transaction_reference ?? null;
        $order->delivery_charge = $delivery_charge;
        $order->delivery_address_id = $order_type == 'home_delivery' ? $customer_address->id : null;
        $order->updated_at = now();
    
        try {
            // Save the updated order
            $order->save();
    
            // Clear session data if needed
            session()->forget('cart');
            session(['last_order' => $order->id]);
            session()->forget('customer_id');
            session()->forget('branch_id');
            session()->forget('table_id');
            session()->forget('people_number');
            session()->forget('address');
            session()->forget('order_type');
    
            Toastr::success(translate('Order updated successfully'));
    
            //send notification to kitchen
            //if ($order->order_type == 'dine_in') {
                $notification = $this->notification;
                $notification->title = "You have a new update in order " . $order_id . " from POS - (Order Confirmed). ";
                $notification->description = $order->id;
                $notification->status = 1;

                try {
                    Helpers::send_push_notif_to_topic($notification, "kitchen-{$order->branch_id}", 'general');
                    Toastr::success(translate('Notification sent successfully!'));
                } catch (\Exception $e) {
                    Toastr::warning(translate('Push notification failed!'));
                }
            //}
            //send notification to customer for home delivery
            if ($order->order_type == 'delivery'){
                $value = Helpers::order_status_update_message('confirmed');
                $customer = $this->user->find($order->user_id);
                $fcm_token = $customer?->fcm_token;

                if ($value && isset($fcm_token)) {
                    $data = [
                        'title' => translate('Order'),
                        'description' => $value,
                        'order_id' => $order_id,
                        'image' => '',
                        'type' => 'order_status',
                    ];
                    Helpers::send_push_notif_to_device($fcm_token, $data);
                }

                //send email
                $emailServices = Helpers::get_business_settings('mail_config');
                if (isset($emailServices['status']) && $emailServices['status'] == 1) {
                    Mail::to($customer->email)->send(new \App\Mail\OrderPlaced($order_id));
                }
            }
    
            // Redirect back to wherever needed
            return redirect()->route('admin.pos.index');
        } catch (\Exception $e) {
            info($e);
            Toastr::warning(translate('Failed to update order'));
            return back();
        }
    }

Error

   POST https://food.sarmadengineeringsolutions.com/admin/pos/update-cart-items 500 (Internal Server Error)

This error occurs when I write $order->id in form action. This id is coming from edit function that triggered when edit button of order is triggered

Edit Controller

public function edit(Request $request, $id)
{
    session()->forget('cart');
    session()->forget('orderid');
    $selected_branch = session()->get('branch_id') ?? 1;
    session()->put('branch_id', $selected_branch);

    $category = $request->query('category_id', 0);
    $categories = $this->category->active()->get();
    $keyword = $request->keyword;
    $key = explode(' ', $keyword);

    $selected_customer = $this->user->where('id', session('customer_id'))->first();
    $selected_table = $this->table->where('id', session('table_id'))->first();
    $tables = $this->table->where(['is_active' => 1, 'branch_id' => $selected_branch])->get();

    $products = $this->product
        ->with(['branch_products' => function ($q) use ($selected_branch) {
            $q->where(['is_available' => 1, 'branch_id' => $selected_branch]);
        }])
        ->whereHas('branch_products', function ($q) use ($selected_branch) {
            $q->where(['is_available' => 1, 'branch_id' => $selected_branch]);
        })
        ->when($request->has('category_id') && $request['category_id'] != 0, function ($query) use ($request) {
            $query->whereJsonContains('category_ids', [['id' => (string)$request['category_id']]]);
        })
        ->when($keyword, function ($query) use ($key) {
            return $query->where(function ($q) use ($key) {
                foreach ($key as $value) {
                    $q->orWhere('name', 'like', "%{$value}%");
                }
            });
        })
        ->active()
        ->latest()
        ->paginate(Helpers::getPagination());

    $current_branch = $this->admin->find(auth('admin')->id());
    $branches = $this->branch->select('id', 'name')->get();

    $order = $this->order->with('details')->where(['id' => $id])->first();
    
    if (!$order) {
    return response()->json(['error' => 'Order not found'], 404);
}

// Initialize variables for calculations
$subtotal = 0;
$discount_on_product = 0;
$addon_price = 0;
$addon_total_tax = 0;
$total_tax = 0;

// Iterate over the order details
foreach ($order->details as $orderDetail) {
    
    // Calculate product subtotal and discounts
    $product_subtotal = $orderDetail->price * $orderDetail->quantity;
    $discount_on_product += $orderDetail->discount * $orderDetail->quantity;
    $subtotal += $product_subtotal;
    $addon_price += $orderDetail->addon_price;
    $addon_total_tax += $orderDetail->addon_total_tax;

    // Calculate total tax for the product
    $product = $orderDetail->product;
    $total_tax += Helpers::tax_calculate($product, $orderDetail->price) * $orderDetail->quantity;

    // Construct data for adding to session cart
    $data =[
        'id' => $orderDetail->product->id,
        'quantity' => $orderDetail->quantity,
        'price' => $orderDetail->price,
        'name' => $orderDetail->product->name,
        'discount' => $orderDetail->discount,
        'image' => $orderDetail->product->image,
        'add_ons' => [],//explode(',', $orderDetail->add_on_ids),
        'add_on_qtys' => [], // You may need to fetch this from somewhere
        'add_on_prices' => [], // You may need to fetch this from somewhere
        'add_on_tax' => [], // You may need to fetch this from somewhere
        'addon_price' => $orderDetail->addon_price,
        'addon_total_tax' => $orderDetail->addon_total_tax,
        'variation_price' => 0,
        'variations' => [],
        'variant' => ''
        // Add other necessary fields here
    ];
    
    if (session()->has('cart')) {
        $cart = session()->get('cart', collect([]));
        $cart->push($data); // Push the data into the cart
        session(['cart' => $cart]);
        //session()->put('cart', $cart);
    } else {
        $cart = collect([$data]);
        session(['cart' => collect([$data])]);
        //session()->put('cart', collect([$cart]));
    }
}

    // Just before returning the view, dump the order object or its ID
    //dd($order); // or 
    //dd($order->id);
    if (session()->has('orderid')) {
        $orderid = session()->get('orderid', collect([]));
        $orderid->push($order->id); // Push the data into the cart
        session()->put('orderid', $orderid);
    } else {
        $orderid = collect([$order->id]);
        session()->put('orderid', collect([$orderid]));
    }
    
    return view('admin-views.pos.edit', compact('order', 'categories', 'products', 'category', 'keyword', 'current_branch', 'branches', 'selected_customer', 'selected_table', 'tables'));
}

Let me also provide update_cart_item controller along with related JavaScript query for better understanding.

AddToCart js Function

function addToCart(form_id = 'add-to-cart-form') {
        if (checkAddToCartValidity()) {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                }
            });
            $.post({
                url: '{{ route('admin.pos.add-to-cart') }}',
                data: $('#' + form_id).serializeArray(),
                beforeSend: function () {
                    $('#loading').show();
                },
                success: function (data) {
                    console.log(data.data)
                    if (data.data == 1) {
                        Swal.fire({
                            confirmButtonColor: '#FC6A57',
                            icon: 'info',
                            title: '{{translate("Cart")}}',
                            confirmButtonText:'{{translate("Ok")}}',
                            text: "{{translate('Product already added in cart')}}"
                        });
                        return false;
                    } else if (data.data == 0) {
                        Swal.fire({
                            confirmButtonColor: '#FC6A57',
                            icon: 'error',
                            title: '{{translate("Cart")}}',
                            confirmButtonText:'{{translate("Ok")}}',
                            text: '{{translate('Sorry, product out of stock')}}.'
                        });
                        return false;
                    }
                    else if (data.data == 'variation_error') {
                        Swal.fire({
                            confirmButtonColor: '#FC6A57',
                            icon: 'error',
                            title: 'Cart',
                            text: data.message
                        });
                        return false;
                    }
                    $('.call-when-done').click();

                    toastr.success('{{translate('Item has been added in your cart')}}!', {
                        CloseButton: true,
                        ProgressBar: true
                    });

                    updateEditCart();
                },
                complete: function () {
                    $('#loading').hide();
                }
            });
        } else {
            Swal.fire({
                confirmButtonColor: '#FC6A57',
                type: 'info',
                title: '{{translate("Cart")}}',
                confirmButtonText:'{{translate("Ok")}}',
                text: '{{translate('Please choose all the options')}}'
            });
        }
    }

updateEditCart js Function

function updateEditCart() {
        console.log('inupdateEditCart');
        $.post('<?php echo e(route('admin.pos.update_cart_items')); ?>', {_token: '<?php echo e(csrf_token()); ?>'}, function (data) {
            $('#cart').empty().html(data);
            console.log('moreinside');
        });
    }

update-cart-items controller

public function update_cart_items(): Renderable
{
    return view('admin-views.pos._update_cart');
}

Now you can see I provided about all related code. I debug code at every stage. Order Id is coming successfully from edit controller upto _update_cart.blade.php file. Guide me what is the issue. If you required any other information you can ask

1

There are 1 best solutions below

0
Sarmad Engineering Solutions On

This issue was resolved after I changed the pattern of retrieving order->id. Instead of calling order->id in the form action, I used it in a jQuery function. This approach worked. Here is the code that I used.

Form

<form action="javascript:void(0)"  method="post" id="order_form" enctype="multipart/form-data">
        @csrf
        <input type="text" id="fororderid" value="{{$order->id}}">
        <div class="pt-4 mb-4">
            
        <div class="row mt-4 gy-2">
            
            <div class="col-md-6">
                    <button type="submit" onclick="updateOrder()" class="btn btn-primary btn-block">
                        <i class="fa fa-shopping-bag"></i>
                        {{translate('Update_Order')}}
                    </button>
            </div>
        </div>
    </form>

JQuery Function

function updateOrder() {
        var id = $('#fororderid').val(); // assuming you have an input field to get the ID
        $.ajax({
            url: "{{ route('admin.pos.update_order') }}",
            type: "POST",
            data: {
                _token: '{{ csrf_token() }}',
                id: id
            },
            success:function(response){
                // handle the response from the server
                console.log(response);
                console.log('success');
            },
            error:function(){
                console.log("error");
                console.log(id);
            }
        });
    }

Controller Function

public function update_order(Request $request)
{
    $id = $request->input('id');
    try {
    // Fetch the order based on the provided ID
    $order = Order::findOrFail($id);

    // Add your logic to update the order here

    // For example:
    // $order->status = 'updated';
    // $order->save();

    // Return a success response
    return response()->json(['success' => true, 'message' => 'Order updated successfully']);
} catch (\Exception $e) {
    // Return an error response if the order is not found or any other error occurs
    return response()->json(['success' => false, 'message' => 'Failed to update order']);
}
}

I don't know the exact reason that why form action cannot get id and why it works when I use JQuery. If anyone can explain the reason, it will be very helpful.