想要使用laravel将产品展示到购物车中

时间:2019-11-28 12:44:06

标签: php laravel

我正在尝试在购物车上显示商品,但遇到一些错误,如何解决?

  

非静态方法Gloudemans \ Shoppingcart \ Cart :: add()不应为   静态称为https://flareapp.io/share/w5BGAXm8#F43

控制器

public function cart()
{
   $cart_list = Cart::Content();
   $cart_data = [];
    foreach($cart_list as $cart){
     $cart_data [] = [
     'product_name' => $cart->product_name,
     'product_image' => $cart->product_image,
     'qty' => $cart->qty,
     'product_price' => $cart->product_price,
     ];
   }
     return view('front_end/cart')->with(compact(['cart_data']));
 }


public function addcart(Request $request){
     $productId=$request->id;
     $productById = DB::table('products')->where('id', $productId)->first(); // Get all 
       Cart::add([
                 'id'=>  $productId,
                 'product_name'=>$productById->product_name,
                 'product_price'=>$productById->product_price,
                 'qty'=>$request->qty,
                 'product_image'=>$productById->product_image,
                ]);
   return redirect('/cart');

2 个答案:

答案 0 :(得分:2)

在您的控制器中:

public function cart()
{
    return view('frontend/cart');
}

public function addCart(Request $request)
{
    $product = Product::findOrFail($request->id);

    $cartItem = Cart::add([
         'id' => $product->id,
         'name' => $product->name,
         'qty' => $request->qty,
         'price' => $product->price,
     ]);

     Cart::associate($cartItem->rowId, 'App\Product');

     return redirect()->route('cart');
}

使用associate()方法,您要告知购物车其中的某个商品与产品模型相关联。

然后,您可以执行以下操作:

@foreach (Cart::content() as $item)
    // your code here
    // but try to access your values as $item->rowId, $item->name, $item->qty, $item->price

@endforeach

然后针对产品图片,您可以执行以下操作:

<img src="{{ asset($item->model->image) }}" alt="product">

答案 1 :(得分:1)

使用create方法

  Cart::create([
                 'id'=>  $productId,
                 'product_name'=>$productById->product_name,
                 'product_price'=>$productById->product_price,
                 'qty'=>$request->qty,
                 'product_image'=>$productById->product_image,
                ]);
   return redirect('/cart');