0

I am having problems working with request cookies on my project. I have a cookie collection with about 3 values a, b, and c. Then I try the following for instance:

$cookieCollection = $this->getRequest()->getCookieCollection();
if ($cookieCollection->has('b')) {
    $cookieCollection->remove('b');
}

After doing this the ‘b’ is removed only from this instance:

$cookieCollection.

But it is still there in

$this->getRequest()->getCookieCollection();

Now how do I update the CookieCollection so that ‘b’ will no longer exist anywhere in the entire site?

I_am_NHO
  • 27
  • 8

1 Answers1

0

Request objects are immutable, and so are cookie collections (and responses for that matter). You'd have to assign a new request object with the new cookie collection, like:

// ...
$cookieCollection = $cookieCollection->remove('b');
$this->request = $this->request->withCookieCollection($cookieCollection));

And if you need this to be available everywhere, then I'd suggest considering to remove the cookies at middleware level:

function (\Psr\Http\Message\ServerRequestInterface $request, $response, $next) {
    $cookies = $request->getCookieParams();
    if (isset($cookies['b'])) {
        unset($cookies['b']);
        $request = $request->withCookieParams($cookies);
    }

    return $next($request, $response);
}

See also

ndm
  • 54,969
  • 9
  • 66
  • 105