Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
suncoastkid Avatar asked Jun 30 '15 17:06

suncoastkid


3 Answers

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');
        }

    }
like image 126
suncoastkid Avatar answered Nov 09 '22 14:11

suncoastkid


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

like image 3
pinkal vansia Avatar answered Nov 09 '22 12:11

pinkal vansia


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.

like image 1
BalmainRob Avatar answered Nov 09 '22 12:11

BalmainRob