Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jpmg's avatar
Level 13

Problem with Cookie in API

I have this method to create a cookie in an API using Laravel 9.

   public function activateCookie(int $digitalpoint)
     {
          $this->digitalpoint = $digitalpoint;
           return response()->json(['Cookie set successfully.'])->withCookie(
              cookie('DigitalIdCookie', $this->digitalpoint)
            );
     }

If I do a dd(), I can see that the cookie is created, the problem is that when I try to read the cookie from another method like for example.

 public function validCookiepoint()
 {
        dd(Cookie::get('DigitalIdCookie'));
}

no matter what i do i always get null, some help please!!!

0 likes
2 replies
JohnH's avatar

I'll take a stab at this. I think it might be a sequencing problem.

In the first snippet, you're adding a cookie to the response headers. The cookie will be sent to your browser if you don't dd() first, and then will be returned to the app from the browser on the next request.

In the second snippet, you're reading from the request headers. This means you're inspecting cookies that came from the browser.

If you're trying to write to the response headers and read from the request headers without the round trip from the app to the browser and back again, you'll never see anything in the second snippet.

1 like
jpmg's avatar
Level 13

@JohnH thank you for your comment it makes sense...

1 like

Please or to participate in this conversation.