ethar
1 week ago
115
3
Laravel

cookies in laravel

Posted 1 week ago by ethar

hi, I'm PHP developer, but newbie in Laravel, I used this code (Pure PHP), to store products in cookies,

if cookies not exist, will create it and store product_id, qty.
if cookies exist, will add product_id, qty to cookies.
if cookies exist and product_id exist, will update qty.

I want to ask if in laravel can improve or simplify this code

    public function addToCart($pid,$qty){
        if(isset($_COOKIE["shopping_cart_panorama"])){
            $cookie_data=stripslashes($_COOKIE["shopping_cart_panorama"]);
            $cart_data=json_decode($cookie_data,true);
        }else{
            $cart_data = array();
        }
        $item_id_list=array_column($cart_data,'item_id');
        if(in_array($pid,$item_id_list)){
            foreach ($cart_data as $keys => $values){
                if($cart_data[$keys]["item_id"] == $pid){
                    $cart_data[$keys]["item_qty"] = $cart_data[$keys]["item_qty"] + $qty;
                }
            }
        }else{
            $item_array = array(
                'item_id' => $pid,
                'item_qty' =>$qty,
            );
            $cart_data[] = $item_array;
        }
        $item_data = json_encode($cart_data);
        $setCookies = @setcookie('shopping_cart_panorama', $item_data, time() + (3600 * 24 * 30),"/");
    }

Please sign in or create an account to participate in this conversation.