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)
}
});
}
}