Laravel购物车对所有用户都是一样的

时间:2017-08-25 11:54:44

标签: php laravel

所以我尝试用laravel创建一个商店,但我的购物车有问题。如果用户在购物车中添加商品,则会更改所有用户。因此,如果我添加一个项目,然后从用户X注销并登录到用户Y,则他们具有相同的购物车 我对Laravel不知何故,我真的不知道这里的问题是什么。感谢帮助!

<?php

namespace App;

class Cart
{
    public $items = null;
    public $totalQty = 0;
    public $totalPrice = 0;
    public function __construct($oldCart)
    {
        if ($oldCart) {
            $this->items = $oldCart->items;
            $this->totalQty = $oldCart->totalQty;
            $this->totalPrice = $oldCart->totalPrice;
        }
    }
    public function add($item, $id) {
        $storedItem = ['qty' => 0, 'price' => $item->price, 'item' => $item];
        if ($this->items) {
            if (array_key_exists($id, $this->items)) {
                $storedItem = $this->items[$id];
            }
        }
        $storedItem['qty']++;
        $storedItem['price'] = $item->price * $storedItem['qty'];
        $this->items[$id] = $storedItem;
        $this->totalQty++;
        $this->totalPrice += $item->price;
    }
    public function reduceByOne($id) {
        $this->items[$id]['qty']--;
        $this->items[$id]['price'] -= $this->items[$id]['item']['price'];
        $this->totalQty--;
        $this->totalPrice -= $this->items[$id]['item']['price'];
        if ($this->items[$id]['qty'] <= 0) {
            unset($this->items[$id]);
        }
    }
    public function removeItem($id) {
        $this->totalQty -= $this->items[$id]['qty'];
        $this->totalPrice -= $this->items[$id]['price'];
        unset($this->items[$id]);
    }
}

产品控制器

<?php

namespace App\Http\Controllers;

use App\Cart;
use App\Product;
use Illuminate\Http\Request;
use Session;
use Illuminate\Support\Facades\DB;

class ProductController extends Controller
{
    public function getIndex()
    {
        $products = Product::all();
        return view('shop.index', ['products' => $products]);
    }

    public function getAddToCart(Request $request, $id){
        $product = Product::find($id);
        $oldCart = Session::has('cart') ? Session::get('cart'): null;
        $cart = new Cart($oldCart);
        $cart->add($product, $product->id);

        $request->session()->put('cart', $cart);
        return redirect()->route('product.index');
    }

    public function getAddQty(Request $request, $id){
        $product = Product::find($id);
        $oldCart = Session::has('cart') ? Session::get('cart'): null;
        $cart = new Cart($oldCart);
        $cart->add($product, $product->id);

        $request->session()->put('cart', $cart);
        return redirect()->route('product.shoppingCart');
    }

    public function getReduceByOne($id) {
        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);
        $cart->reduceByOne($id);
        if (count($cart->items) > 0) {
            Session::put('cart', $cart);
        } else {
            Session::forget('cart');
        }
        return redirect()->route('product.shoppingCart');
    }

    public function getRemoveItem($id) {
        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);
        $cart->removeItem($id);
            if (count($cart->items) > 0) {
                Session::put('cart', $cart);
            } 
            else {
                Session::forget('cart');
            }
        return redirect()->route('product.shoppingCart');
    }

    public function getCart(){
        if(!Session::has('cart')){
            return view('shop.shopping-cart');
        }
        $oldCart = Session::get('cart');
        $cart = new Cart($oldCart);
        $total = $cart->totalPrice;
        $count = count($cart->items);
        Session::put('cart', $cart);
        return view('shop.shopping-cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice, 'total' => $total, 'count' => $count]);
    }

    public function getCheckout()
    {
        if(!Session::has('cart')){
            return view('shop.shopping-cart');
        }
    $oldCart = Session::get('cart');
    $cart = new Cart($oldCart);
    $total = $cart->totalPrice;
    return view('shop.checkout',[ 'total' => $total]);
    }

    public function deleteProduct(Request $request, $id){
        $product = Product::find($id);
        $oldCart = Session::has('cart') ? Session::get('cart'): null;
        $cart = new Cart($oldCart);

        session()->pull('product', $product->id);
        $request->session()->put('cart', $cart);

        return redirect()->route('product.shoppingCart');
    }
}

用户控制器

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
Use Session;
use App\Cart;

class UserController extends Controller
{
    public function getSignup()
    {
        return view('user.signup');
    }

    public function postSignup(Request $request)
    {
        $this->validate($request, [
            'sex' => 'required',
            'firstname' => 'required',
            'lastname' => 'required',
            'email' => 'email|required|unique:users',
            'password' => 'required|min:4'
        ]);

        $user = new User([
            'sex' => $request->input('sex'),
            'firstname' => $request->input('firstname'),
            'lastname' => $request->input('lastname'),
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password'))
        ]);
        $user->save();
        Auth::login($user);

        return redirect()->route('user.profile');
    }
    public function getSignin()
    {
        return view('user.login');
    }

    public function postSignin(Request $request){
        $this->validate($request, [
            'email' => 'email|required',
            'password' => 'required|min:4'
        ]);

    if(Auth::attempt([
        'email' => $request->input('email'), 
        'password' => $request->input('password')])){

        return redirect()->route('user.profile');
    }
        return redirect()->back();
    }

    public function getProfile(){
        $user = User::all();

        return view('user.profile',['user' => $user]);
    }

    public function getLogout(){

        Auth::logout();

        return redirect()->route('product.index');
    }
}

1 个答案:

答案 0 :(得分:0)

如果使用相同的选项卡切换用户,则Laravel会话变量仍然存在。 因此,如果您保存属于用户X的任何会话变量,当用户Y登录时,它仍将存在。Reference

因此,当用户使用Session::forget('cart');

注销时,您需要显式删除User X的会话
$user_id = /*get user_id*/;
Session::put($user_id.'cart', $cart);

但是,这会产生一个问题,每当用户退出您的应用程序时,他/她的购物车将是空的。要解决此问题,您可能需要将购物车与用户ID相关联。

一种方法是将user_id添加到会话变量的密钥中。

将购物车添加到会话时:

$user_id = /*get user_id*/;
Session::get($user_id.'cart', $cart);

检索购物车时:

  <script type="text/javascript">

     var sess_pollInterval = 60000;
     var sess_expirationMinutes = 20;
     var sess_warningMinutes = 15;
     var sess_intervalID;
     var sess_lastActivity;

     function initSession() {
         sess_lastActivity = new Date();
         sessSetInterval();
         $(document).bind('keypress.session', function (ed, e) {
             sessKeyPressed(ed, e);
         });
     }

     function sessSetInterval() {
         sess_intervalID = setInterval('sessInterval()', sess_pollInterval);
     }

     function sessClearInterval() {
         clearInterval(sess_intervalID);
     }

     function sessKeyPressed(ed, e) {
         sess_lastActivity = new Date();
     }

     function sessLogOut() {
         window.location.href = 'Default.aspx';
     }

     function sessInterval() {
         var now = new Date();
         //get milliseconds of differneces 
         var diff = now - sess_lastActivity;
         //get minutes between differences
         var diffMins = (diff / 1000 / 60);

         if (diffMins >= sess_warningMinutes) {
             //wran before expiring
             //stop the timer
             sessClearInterval();
             //promt for attention
             var active = confirm('Your session will expire in ' + (sess_expirationMinutes - sess_warningMinutes) +
                 ' minutes (as of ' + now.toTimeString() + '), press OK to remain logged in ' +
                 'or press Cancel to log off.');
             if (active == true) {
                 now = new Date();
                 diff = now - sess_lastActivity;
                 diffMins = (diff / 1000 / 60);

                 if (diffMins > sess_expirationMinutes) {
                     sessLogOut();
                 }
                 else {
                     initSession();
                     sessSetInterval();
                     sess_lastActivity = new Date();
                 }
             }
             else {
                 sessLogOut();
             }
         }
     }
    </script>

我认为您应该创建用于存储购物车的表并使用外键来引用用户,而不是使用会话来存储购物车。