2

I am trying to set a cookie in an ajax call, but can't get it to work. I have understood that I need to set it via setCookie on $response->headers. The $cookie variable looks correct, but no cookie is set in the browser.

Code from my controller:

$cookie = Cookie::make('testcookie', array('testvalue' => 'test'), 1000);  
$response = Response::json(array('status' => 'ok'));  
$response->headers->setCookie($cookie);  
return $response;

1 Answers1

3

I think you are calling this function after the page is initialized. So no cookie headers can be sent after the html tags started.

Refer to this Link

and this will help you

Community
  • 1
  • 1
Dan Jay
  • 874
  • 10
  • 27
  • I verified that no output has been done when I try to set the cookie. The problem seems to be that I am trying to set the cookie in an ajax-call? – Mattias Hallström Apr 07 '14 at 05:33
  • 2
    I hate my self right now :-) You are so correct shan! By accident one of my classes had a blank space before the opening php-tag. Removing that solved the whole thing :-) It's strange that I didn't see any errors from laravel similar to the normal you get from setcookie when content has already been sent. Thanks a million!!!! – Mattias Hallström Apr 07 '14 at 05:48
  • 1
    @user3505343 : no worries :) we all do silly mistakes all the time. Glad your problem solved. Good luck with your project. – Dan Jay Apr 07 '14 at 05:50
  • so, what is the answer? i still confused that my cookies not changed with json – Abdan Syakuro Jun 17 '20 at 04:10