How to create cookies in cakephp 4x or 5x

hey everyone i need to know how does create cookies in cakephp 4x or 5x?

Blockquote
$cookie = (new Cookie(‘abcd’))
->withValue(‘892020’)
->withExpiry(new DateTime(‘+1 year’))
->withPath(‘/’)
->withDomain($domain)
->withSecure(false)
->withHttpOnly(true);
$cookies = new CookieCollection([$cookie]);
$cookies->add($cookie);

So I just do some code for create cookie but it is not working. when i open new page get try to read cookie like this

Blockquote
$getCookie = $this->request->getCookie(‘abcd’);

but its is not working i have got null value response. please help me how create cookie and how can i get this cookie in another controller or method please please me out guys

You’re creating a cookie, but not adding it to the response. See setting cookies in the manual.

thank for reply and suggestion @Zuluru so now i did it same as mention in cakephp Docs

Blockquote
public function CA()
{
$cookie = (new Cookie(‘abcd’))
->withValue(‘4582ATC’)
->withExpiry(new DateTime(‘+1 year’))
->withPath(‘/’)
->withDomain($domain)
->withSecure(false)
->withHttpOnly(true);
$cookies = new CookieCollection([$cookie]);
$cookies->add($cookie);
$this->response = $this->response->withCookie($cookie);
}

but i got same result as before NULL in different method.

Blockquote
public function CB(){
$cookie = $this->request->getCookie(‘abcd’);
dd($cookie);
}

CB method return null value. even this function not help me
$response = $this->response->withCookieCollection($cookies);

Not sure if it’s related, but your function calls ->withDomain($domain) but you have not defined $domain in anything shown here.

Also, check your browser developer tools to inspect the response coming back from loading the CA page, to see whether the cookie is being set or not. That will narrow down whether the problem is in setting it or reading it.

$domain is nothing its just site URL Exp: http://example.com. @Zuluru CA and CB are in same controller methods so when i call CA method it just store cookie and redirect to CB method in same controller method… but in CB method does not show me cookie values. I think its CAKEPHP BUG.

Blockquote
public function CA()
{
$cookie = (new Cookie(‘abcd’))
->withValue(‘4582ATC’)
->withExpiry(new DateTime(‘+1 year’))
->withPath(‘/’)
->withDomain(‘/’)
->withSecure(false)
->withHttpOnly(true);
$cookies = new CookieCollection([$cookie]);
$cookies->add($cookie);
$this->response = $this->response->withCookie($cookie);
}
public function CB(){
$cookie = $this->request->getCookie(‘abcd’);
dd($cookie);
}

now you can check I just remove $domain variable and put there / which its base path for whole Web Application but still not working. Cookie not create Bro it just show me in only in CA method not in another method. please let me show some code for cookies in cakephp

hahahhaha Problem solved @Zuluru read again docs and I get something so now my program run very well thanks man you replied me and suggestion