Glidarn Glidarn - 1 month ago 25
PHP Question

Set a cookie in Laravel 5+ without response

I'm trying to set a cookie in a function that's not going to return a response. The function is called from a middleware.

Middleware:

// Verify user
$userId = $userService->verify($email, $key);
if ($userId) {
$userService->authenticate($userId, $key);

return $next($request);
} else {
return response('Unauthorized', 401);
}


is calling $userService->authenticate:

// Get user
$user = $this->getById($id);
// Get user zipcode
$user->zipcode = $this->getZipcodeById($id);
// Set session
Session::set('user', $user);

if (!Cookie::has('user_forever')) {
// SET COOKIE
}


I have tried to return a response in authenticate but it doen't work. I can't get it to work.. So I appreciates all help!

Thanks in advance

Answer

You can use queue() as:

Cookie::queue('key', 'value', 10);