我试图将产品添加到我的CartController中当前登录的用户购物车中,但是当我点击“添加到购物车”按钮时,它会抛出以下异常:警告:
为foreach()提供的参数无效
这是我的addToCart功能:
/**
* @Route("/cart/add", name="cart_add")
*/
public function addToCartAction(Request $request)
{
$manager = $this->getDoctrine()->getManager();
$currentUserId = $this->get('security.token_storage')->getToken()->getUser();
$session = $this->get('session');
$id_cart = $session->get('id_cart', false);
if (!$id_cart) {
$cart = new Cart();
$cart->setUserId($currentUserId);
$cart->setDateCreated(new \DateTime());
$cart->setDateUpdated(new \DateTime());
$manager->persist($cart);
$manager->flush();
$session->set('id_cart', $cart->getId());
}
$cart = $this->getDoctrine()->getRepository('AppBundle:Cart')->find($session->get('id_cart', false));
$products = $request->get('products');
foreach ($products as $id_product) {
$product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($id_product);
if($product) {
$cartProduct = new CartProduct();
$cartProduct->setCart($cart);
$cartProduct->setProduct($product);
$cartProduct->setQuantity(1);
$manager->persist($cartProduct);
}
}
$cart->setDateUpdated(new \DateTime());
$manager->persist($cart);
$manager->flush();
return $this->redirectToRoute('cart_list');
}
答案 0 :(得分:1)
获取参数时应添加默认值以避免出现这类错误:
namespace App\Http\Controllers\Panel;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class AuthController extends Controller
{
public function Login(Request $request)
{
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
return view('admin.login');
}
public function Auth(Request $request)
{
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
dump($request->all());
echo "Received";
}
}