Home > Blockchain >  How to set multiple cookies with one response in Laravel?
How to set multiple cookies with one response in Laravel?

Time:08-09

I am trying to send multiple cookies with one response. I have an array with cookies named

$cookies

What would be an alternative of the following example if I have an array with values instead of specific values

return $response
   ->withCookie(cookie()->forever('region', $region))
   ->withCookie(cookie()->forever('somethingElse', $somethingElse));

I have tried the following code but it does not seem to work.

       $response = $this->response(200, 'Successful');

       foreach($cookies as $cookie){
           $response = $response->withCookie($cookie);
       }

       return $response;

CodePudding user response:

Just save the cookies via the Cookie::queue() method.

Then you can access the cookies anywhere via the Cookie::get() method afterwards.

You won't need to add them to the response if you do it this way, and they will still be accessible inside of views etc.

CodePudding user response:

Try adding this function inside "vendor\laravel\framework\src\Illuminate\Http\Response.php". The function adds and removes multiple cookies in one response.

/**


* Add cookies to the response.
 *
 * @param Array of  $cookie
 * @return \Illuminate\Http\Response
 */
public function withCookies(Array $cookies)
{
    foreach($cookies as $cookie)
        $this->headers->setCookie($cookie);

    return $this;
}
  • Related