Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 JSON Response with Cookie

Tags:

json

How can I set a cookie with a json response?

I noticed, for me at least, the following command is the only thing working that sets a cookie:

            return Redirect::to('/')
                ->withCookie(Cookie::make('blog', $cookie_values, 1000));

Of course if it was an ajax request it would return the target of the redirect.

How could I translate this to an ajax request and return a json response with the cookie?

like image 544
user2094178 Avatar asked Feb 21 '13 06:02

user2094178


1 Answers

I was able to set a cookie with a json response with the following code:

            $cookie_values = array(
                'name' => Input::get('name'),
                'id' => Auth::user()->id,
                'login_success' => 1);

            if(Request::ajax())
            {                    
                $cookie = Cookie::make('blog', $cookie_values, 1000);
                $response = Response::json($cookie_values);
                $response->headers->setCookie($cookie);

                return $response;
            }
like image 175
user2094178 Avatar answered Sep 24 '22 15:09

user2094178