【发布时间】:2020-04-04 19:52:02
【问题描述】:
请我需要关于 angular 9 的 laravel 帮助,我试图将产品从前端添加到购物车到后端,这是使用 api 路由的 laravel。当我点击添加到购物车按钮时,没有任何东西添加到购物车,下面是我的代码:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
use App\Product;
use App\Cart;
class ProductController extends Controller
{
public function addToCart(Request $request, $id){
$product = Product::find($id);
$cart = session()->get('cart');
// if cart is empty then this the first product
if(!$cart) {
$cart = [
$id => [
"name" => $product->name,
"quantity" => 1,
"price" => $product->price,
"photo" => $product->image
]
];
session()->put('cart', $cart);
return response()->json(['success'=> 'Product has been added to cart']);
}
// if cart not empty then check if this product exist then increment quantity
if(isset($cart[$id])) {
$cart[$id]['quantity']++;
session()->put('cart', $cart);
return response()->json(['success'=> 'Product has been added to cart']);
}
// if item not exist in cart then add to cart with quantity = 1
$cart[$id] = [
"name" => $product->name,
"quantity" => 1,
"price" => $product->price,
"photo" => $product->image
];
session()->put('cart', $cart);
return response()->json(['success'=> 'Product has been added to cart']);
}
}
请帮忙。
【问题讨论】: