当我尝试在vue.js和laravel中使用axios添加购物车时,我没有收到任何错误,但在响应中返回一个空数组,并且会话未设置。
Vue - Axios请求
cartSession(){
if(this.checked){
axios.post('http://localhost:8000/cart/cart/'+this.checked[0],{
'id':this.checked[0],
'category':this.checked[2],
'service_plan':this.checked[3],
'price':this.checked[1],
'user_id':this.checked[4]
})
.then(data=>this.sessionCart = data)
.catch(error => {
console.log(error.message);
})
}else {
this.sessionCart = " ";
}
}
控制器
public function cart(Request $request,$id){
$session = $request->session();
$service = array(
'id'=>$request->id,
'category'=>$request->category,
'service_plan'=>$request->service_plan,
'price'=>$request->price,
'user_id'=>$request->user_id
);
$services = (object)$service;
$oldCart = $session->has('cart') ? $session->get('cart') : null;
$carts = new CartSession($oldCart);
$carts->add($service,$id);
$session->put('cart', $carts);
$sessionData = $session->get('cart');
return request()->json(200,$oldCart);
// dd($service);
//return request()->json(200,$service);
}
购物车型号
class CartSession extends Model
{
public $serviceCategory = null;
public $servicePlan = 0;
public $price = 0;
public $totalPrice = 0;
public $serviceTotal = 0;
public function __construct($oldCart)
{
//parent::__construct($attributes);
if($oldCart){
$this->serviceCategory = $oldCart->serviceCategory;
$this->servicePlan = $oldCart->servicePlan;
$this->price = $oldCart->price;
$this->totalPrice = $oldCart->totalPrice;
$this->serviceTotal = $oldCart->serviceTotal;
}
}
public function add($item,$id){
$storedItem = ['service_qty'=> 0,'category' => $item['category'],'price'=>$item['price']];
if ($this->serviceCategory){
if(array_key_exists($id,$this->serviceCategory)){
$storedItem = $this->serviceCategory[$id];
}
}
//dd($storedItem);
$storedItem['service_qty']++;
$storedItem['price'] = $item['price'] * $storedItem['service_qty'];
$this->serviceCategory[$id] = $storedItem;
$this->serviceTotal++;
$this->totalPrice += $item['price'];
$this->servicePlan = $item;
return $item;
}