App\Models\Store\Order::cart PHP Method

cart() public static method

public static cart ( $user )
    public static function cart($user)
    {
        $cart = static::query()->where('user_id', $user->user_id)->where('status', 'incart')->with('items.product')->first();
        if ($cart) {
            $requireFresh = false;
            //check to make sure we don't have any invalid products in our cart.
            $deleteItems = [];
            foreach ($cart->items as $i) {
                if ($i->product === null) {
                    $deleteItems[] = $i;
                    continue;
                }
                if (!$i->product->inStock($i->quantity)) {
                    $cart->updateItem(['product_id' => $i->product_id, 'quantity' => $i->product->stock]);
                    $requireFresh = true;
                }
            }
            if (count($deleteItems)) {
                foreach ($deleteItems as $i) {
                    $i->delete();
                }
                $requireFresh = true;
            }
            if ($requireFresh) {
                $cart = $cart->fresh();
            }
        }
        if ($cart) {
            $cart->refreshCost();
        } else {
            $cart = new self();
            $cart->user_id = $user->user_id;
        }
        return $cart;
    }

Usage Example

Example #1
0
 private function userCart()
 {
     if (Auth::check()) {
         return Store\Order::cart(Auth::user());
     } else {
         return new Store\Order();
     }
 }