phplaravelcookieslaravel-4.2

Cookie set is not getting in next refresh


In my laravel 4.2 application, cookie is set via ajax. but on page refresh it is showing that undefined index token ($_COOKIE['token']).

//Add to cart function

setcookie('token', $token);
                $token = $this->getcookie('token');
                if(isset($token)){
                     $cart  = Cart::create([ 'user'   => $token ]); 
                } 



public function getcookie($name) { 
        $cookies = [];
        $headers = headers_list();
        foreach($headers as $header) {
            if (strpos($header, 'Set-Cookie: ') === 0) {
                $value = str_replace('&', urlencode('&'), substr($header, 12));
                parse_str(current(explode(';', $value, 1)), $pair);
                $cookies = array_merge_recursive($cookies, $pair);
            }
        }
        return $cookies[$name];
    }

And cookie is being set . But on page refresh, I'm not getting the set cookie value


Solution

  • You missed to give expier time.

    setcookie('token', $token, time() + (86400 * 30), "/");
    

    It will keep the cookie for 30 days.
    Check This