Reputation: 499
I'm using Laravel 5.2 and tried the following code to set cookie, but the cookie is not set. I checked by seeing Chrome/Safari/FireFox dev tool and also by calling Cookie::get('test') in 'cookie-test' blade template.
class SampleController extends Controller {
public function index() {
echo 'setting cookie...';
$response = new Response(view('cookie-test'));
$response->withCookie('name', 'value', 60);
return $response;
}
}
I also tried other ways introduced on the official document, such as
$response = new Illuminate\Http\Response('Hello World');
$response->withCookie('name', 'value', $minutes);
return $response;
,
$response->withCookie(cookie()->forever('name', 'value'));
,
Cookie::queue(cookie('name', 'value', 60))
and so on, referencing stackoverflow answers too.
Is there anything I'm missing? Any configuration I need to setup in advance? Any good ways to debug this problem?
I'd appreciate any advice, thank you.
Upvotes: 3
Views: 1115
Reputation: 499
I found the cause. Using echo() or var_dump() before returning $response will prevent the application from setting cookie. I used var_dump() in a class called by the constructor of the above Controller for debug, but after I deleted the var_dump() line, cookie was set successfully.
Upvotes: 4