funway's avatar

Cookie setting doesn't work if i use dump() function

Route::get('cookie', function () {
    $response = new Illuminate\Http\Response('Hello World');

    $response->withCookie('apple', '10', 10);

    var_dump(Request::cookie());

    /**
     * if i use the dump function in vendor/symfony/var-dumper/Resources/functions/dump.php
     * then setting cookie will not be working.
     * comments this line, setting cookie will work well.
     */
    dump(123);

    return $response;
});
0 likes
4 replies
SaeedPrez's avatar

Cookies are set in the response header as they are client-side and not server-side (i.e. sessions). So you need to return $response in order for the cookie to work.

funway's avatar

Yes, as you said, i have return $response at the end of the closure. The dump() function not like dd(), it will not exit process. The return line will be executed, but it seems like the dump() function will cut off cookies setting. The cookie['apple'] will not be setted in the response... I don't konw why... =。=#

SaeedPrez's avatar
Level 50

Maybe I didn't explain clear enough, once you send some content to be displayed in the browser, you cannot send a header anymore... so the header (including the cookie) needs to be sent first and then the content .

When you dump(123) you're sending header (without cookie) and content 123 to the browser and then when you return $response the header is already sent and done, so your cookie won't work and it will only show the content.

2 likes
funway's avatar

oh, thanks for your explanation ^_^

Please or to participate in this conversation.