【问题标题】:How to add product to cart using laravel with angular如何使用带有角度的laravel将产品添加到购物车
【发布时间】: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']);
    }
}

请帮忙。

【问题讨论】:

    标签: angular laravel


    【解决方案1】:

    只有一个请求的会话存储数据,您可以将数据推送到缓存中。请点击此链接将数据存储在缓存中https://laravel.com/docs/8.x/cache

    【讨论】:

      猜你喜欢
      • 2019-08-06
      • 1970-01-01
      • 2019-04-28
      • 2012-06-09
      • 1970-01-01
      • 2011-12-19
      • 2017-01-03
      • 2014-11-21
      相关资源
      最近更新 更多