Ɛɔıs3
Ɛɔıs3

Reputation: 7853

Why cookie isn't set in Laravel Lumen

This question is the following of this question.

I have a message in my view who says : This site uses cookie [...] Close.

When user click on Close, an ajax request is send to the controller. The function is the following :

public function acceptCookie(Request $request)
{
    if ($request->valid == 'accept') {
        $response = new Response('acceptCookie');
        if ($response->withCookie(cookie('acceptCookie', 'accepte', 44000))) {
            return Response()->json(array('statut' => 'Succes'));    
        } else {
            return Response()->json(array('statut' => 'Erreur'));
        }            
    } else {
        return Response()->json(array('statut' => 'Erreur'));
    }
}

I haven't any error and JSON returns always {"statut":"Succes"}

Why the cookie isn't set ?

Upvotes: 0

Views: 4122

Answers (2)

krisanalfa
krisanalfa

Reputation: 6438

Based on Illuminate\Http\ResponseTrait line 28, the Illuminate\Http\Response::withCookie method returning $this.

/**
 * Add a cookie to the response.
 *
 * @param  \Symfony\Component\HttpFoundation\Cookie  $cookie
 * @return $this
 */
public function withCookie(Cookie $cookie)
{
    $this->headers->setCookie($cookie);

    return $this;
}

Means you have logic failure in your code.

// This always return Illuminate\Http\Response instance,
// thus it will never reach ELSE statement forever.
if ($response->withCookie(cookie('acceptCookie', 'accepte', 44000))) {
     return Response()->json(array('statut' => 'Succes'));    
} else {
    return Response()->json(array('statut' => 'Erreur'));
}

Upvotes: 0

John Shipp
John Shipp

Reputation: 1153

Based on the Lumen documentation, it appears as though you need to queue the cookie for a response such as the one in your example. Here's what the docs say:

Queueing A Cookie For The Next Response

If you would like to set a cookie before a response has been created, use the Cookie::queue() method. The cookie will automatically be attached to the final response from your application.

Cookie::queue($name, $value, $minutes);

My suggestion would be to try replacing the withCookie with queuing the cookie instead. But, you might need to rewrite the function a bit in order to accomodate because it appears as though you're trying to send to responses from one request.

Hope this works for you!

Upvotes: 2

Related Questions