1

I'm trying to make a shopping cart using laravel 7 and ajax. When i press add product, it save the product into the cart in the database. If the product is already in the cart, it will just add 1 to the quantity. If not, it will create a new order item in the cart. Then, it will return an output variable with html content through json response. Then i append the html data using javascript. The problem is when i add a product and the product isn't in the cart so it created a new order item. The json response doesn't seem to load the latest order item in the html. But when i add that same product the second time, it managed to append the html. Does the foreach didn't get the latest data from database?

This is the function in the controller

public function addItem($product_id, Request $request){
    $order_id = auth()->user()->waitingOrder->first()->id;
    $order = Order::find($order_id);
    $bingo = false; 
    foreach ($order->orderItems as $key => $order_item) { 
      if ($product_id == $order_item->product_id) {
        $order_item->quantity = $order_item->quantity + 1;
        $order_item->save();
        $bingo = true;
        break;
      }
    }
    if ($bingo == false) {
      $new_item = new OrderItem();
      $new_item->order_id = $order_id;
      $new_item->product_id = $product_id;
      $new_item->save();
    }
    $output = "";
    foreach ($order->orderItems as $item) {
      $output .= '<tr>'.
      '<td align="left" width="15%">'.
          '<img style="height: 80px; width: 80px;" src="'. asset('img/products/' . $item->product->image) .'">'.
        '</td>'.
        '<td align="center" width="20%">'.
          $item->product->name .
        '</td>'.
        '<td>'.
          rupiah($item->product->price) .
        '</td>'.
        '<td width="14%">'.
          '<input type="number" class="form-control" name="quantity" value="'. $item->quantity .'" min="1" max="'. $item->product->stock .'">'.
        '</td>'.
        '<td>'.
          rupiah($item->product->price * $item->quantity) .
        '</td>'.
        '<td>'.
          '<a href="'. route('kasir.remove.item', $item->product->id ) .'" class="remove-btn">'.
          '<span class="icon_close"></span>'.
          '</a>'.
        '</td>'.
      '</tr>';
    }
    return response($output);
  }

This is the javascript code

$(document).on('click', '.add-btn', function(event){
        event.preventDefault();
        $.ajax({
            url: $(this).attr('href'),
            success:function(data){
                $('#orderItems').html(data);
            }
        });
    });

    function order(){
        var customer_name = $('#customer_name').val();
        var link = $('#order-btn').attr('href');
        if (link != '#') {
            $.ajax({
                type: 'POST',
                url: link,
                data: {name:customer_name},
                success:function(data){
                    $('#order_id').val(data.order_id);
                    $('#customer_name').prop('disabled', true);
                    $('#order-btn').attr('href', '#');
                    $('#cart-total').html("")
                    $('#cart-total').html(data.output)
                }
            });
        }
    }
Muh Ghifari
  • 23
  • 1
  • 5
  • I don't know laravel or php but I can see that your foreach only works for `$order` and this variable only returns some object if it finds it in db. When you create new object and save it into the database you use `$new_item`. So your foreach doesnt know anything about new row... even if its saved into database. I think you should just use `$order` instead of `$new_item` in your `bingo==false` – sonic Jul 19 '20 at 13:07
  • 1
    `$order->fresh();` or `$order->refresh();` after saving the order item. Depending which version of laravel you are using. – user3647971 Jul 19 '20 at 13:38
  • `$order->load('orderItems');` Might be more specific. Both explained and answered before [here](https://stackoverflow.com/questions/23642950/how-to-reload-refresh-model-from-database-in-laravel) and [here](https://stackoverflow.com/questions/47192035/refresh-the-relationship-without-reloading-the-model) – user3647971 Jul 19 '20 at 13:41
  • @sonic I use $order as a shopping cart, and in $order there are $orderItems in which i store the product_id. So if want to add a product, i have to store it in $orderItems. $new_item is an object of $orderItems. I can't put the product_id in $order. – Muh Ghifari Jul 19 '20 at 13:41
  • 1
    Just to be clear, you are not to be generating html in controllers, you should use views for that part, this is not best practice in any form. – mrhn Jul 19 '20 at 13:47
  • @user3647971 Thank you so much. I add $order->refresh() and it works. I'm guessing when i create a new order item, $order still contains the data before i made the new product. So when i put foreach() it doesn't contain the new one. Thanks to everyone for the reply. – Muh Ghifari Jul 19 '20 at 13:47

0 Answers0