suncoastkid suncoastkid - 4 months ago 33
PHP Question

Laravel 5.1 Cookie Issue

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?

Answer

This works to reliably set a cookie with Laravel:

 use Illuminate\Http\Request;
 use Illuminate\Cookie\CookieJar;

    class MyClass
    {

        public function handle(Request $request, CookieJar $cookieJar)
        {
            $cookieJar->queue(cookie('myCookie', $request->someVal, 129600));
            return redirect('/myPage');
        }

    }