phper
phper

Reputation: 181

How to use cookies with Laravel?

I want to print OK every time user enter website except the first time.

I write that:

$cookie =  Cookie::get('cookie_name');
    if(!isset($cookie) || $cookie != 1) {
        Cookie::forever('cookie_name', 1);
    } else {
        echo 'OK';
    }

but OK not printed in any case.

Upvotes: 0

Views: 828

Answers (1)

kajetons
kajetons

Reputation: 4580

You have to attach the cookie to a response (Response or Redirect object) to actually set it.

Try this:

$cookie =  Cookie::get('cookie_name');

if(!isset($cookie) || $cookie !== 1) {
    $cookie = Cookie::forever('cookie_name', 1);
    return Response::make('Cookie Set!')->withCookie($cookie);
}

return 'OK';

Alternatively you can use Cookie::queue() to attach the cookie to the next response and avoid using withCookie method.

Upvotes: 3

Related Questions