I'm trying to set a cookie when I load a view:
$cookie = Cookie::make('mycookie', $myval, 43200);
$view = view('myview')->with($data);
return Response::make($view)->withCookie($cookie);
And read the cookie on a later request:
if (Cookie::has('mycookie')) {
//do something
}
The cookie never gets set... where am I going wrong?
This works to reliably set a cookie with Laravel:
use Illuminate\Http\Request;
use Illuminate\Contracts\Cookie\Factory;
class MyClass
{
public function handle(Request $request, Factory $cookie)
{
$cookie->queue($cookie->make('myCookie', $request->someVal, 129600));
return redirect('/myPage');
}
}
You can create cookie like following
$view = view('myview')->with($data);
$response = new Illuminate\Http\Response($view);
return $response->withCookie(cookie('name', 'value', $minutes));
Or you can queue the cookie like below, and it will be sent with next request,
Cookie::queue('name', 'value');
return response('Hello World');
Read More
A possible cause of your missing cookie problem could be that if you have a invalid Blade directive the page will display normally however any cookies set will not be persisted.
I encountered this problem as I had included @script
in my blade template rather than @section('script')
I suspect the reason the cookies does get set is that the bad directive causes an error in the compiled php code that the view gets cached as and so the processing crashes before the cookie is transferred.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With