suncoastkid
suncoastkid

Reputation: 2223

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?

Upvotes: 5

Views: 4415

Answers (3)

suncoastkid
suncoastkid

Reputation: 2223

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

    }

Upvotes: 4

BalmainRob
BalmainRob

Reputation: 365

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.

Upvotes: 1

pinkal vansia
pinkal vansia

Reputation: 10310

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

Upvotes: 3

Related Questions