AntoineB
AntoineB

Reputation: 4694

How to use Laravel cookies?

I would like to use Laravel cookies but I cannot seem to make it work.

So basicaly I'd like to make the Laravel equivalent to :

setcookie("TestCookie", $value, time() + 3600 * 24 * 365);
echo $_COOKIE["TestCookie"];

I used this, without success, it's not printing anything :

Cookie::make('TestCookie', $value, 60 * 24 * 365);
echo Cookie::get('TestCookie');

Same goes for

Cookie::queue('TestCookie', $value, 60 * 24 * 365);
echo Cookie::get('TestCookie');

Or

Cookie::forever('TestCookie', $value);
echo Cookie::get('TestCookie');

I'd like to do this in my BaseController __construct method :

if (Session::has('hash') && !Cookie::has('hash'))
{
    Cookie::queue('hash', Session::get('hash'), $this->cookieLifeTime);
}
else if (Cookie::has('hash') && !Session::has('hash'))
    Session::put('hash', Cookie::get('hash'));
else if (!Session::has('hash') && !Cookie::has('hash'))
{
    $hash = str_shuffle(sha1(uniqid()));
    Session::put('hash', $hash);
    Cookie::queue('hash', Session::get('hash'), $this->cookieLifeTime);
}

Thanks :)

Upvotes: 1

Views: 1912

Answers (2)

Danny
Danny

Reputation: 454

Cookie::make only creates new instances of Cookie class.

After you created an instance you should return it with your Response

$cookie = Cookie::make('TestCookie', $value, 60 * 24 * 365);
return Response::view('view')->withCookie($cookie);

Also you can do the same but with Redirect

return Redirect::to('somewhere')->withCookie($cookie)

PS. Note, that cookie will be available only after page restart. And it's same for Cookie:queue(...)

The main difference of Cookie:queue() is that Laravel will automatically attach your Cookie at the end of current Response. But it's still unavailable until next request (page opening)

Update

As per your comments I just tested this code:

Cookie::queue(Cookie::make('test', 'test'));

echo (Cookie::has('test')) ? Cookie::get('test') : 'null';

It works fine.

Update 2

Try set the correct domain name in /app/config/sessions.php It might help in some cases.

Upvotes: 3

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

You need to change:

Cookie::queue('TestCookie', $value, 60 * 24 * 365);
echo Cookie::get('TestCookie');

into:

if (Cookie::has('TestCookie')) {
   echo Cookie::get('TestCookie');
}
else {
    Cookie::queue('TestCookie', $value, 60 * 24 * 365);
}

As in PHP you cannot display cookie if page hasn't been refreshed. So first you set cookie and when you reload your page you should have your cookie set and then application can display its value.

Upvotes: 0

Related Questions