0

I'm having problems to create cookie in Laravel5. The code is below.

            $input = $request->input('first');

            if($request->hasCookie('first'))
            {
                return response()->json('ok');
            }
            else
            {
                Cookie::make('first', 'first', 1);
                return response()->json('no');
            }

I also tried this:

public function createCookie(CookieJar $cookieJar)
{
 $cookieJar->make('first', 'first', 1);
}

Nothing works for me, can someone illuminate me? Thanks in advance. When i try to var_dump and get the cookie value it gives me NULL.

2
  • Is it giving you an error, or are you just not able to read the cookie? Commented Mar 14, 2015 at 19:07
  • I can't read the cookie, when i dd($cokie) it gives me null, so the cookie is not created Commented Mar 14, 2015 at 19:59

2 Answers 2

2

By doing this Cookie::make('first', 'first', 1); , you are creating a cookie it doesn't mean it is already set. you have to send cookie with response. use below code:

$cookie=Cookie::make('first', 'first', 1);
 return response()->json('no')->withCookie($cookie);
Sign up to request clarification or add additional context in comments.

3 Comments

so i must send response with cookie in order to get cookie value?
cookies are stored in browser right !. so by sending response you are telling browser to keep this cookie.
@jignesh-solanki THANK YOU! Why is this not documented better.
0

Cookies are sent only a request after you created them.

An easier way to check if cookie exist or not is to check http headers in the browser or resources->cookies in Chrome.

Also you didn't provide the dd/var_dump code you used or neither why you need to use a new cookie instead of using Laravel Session::flash

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.