Laravel 4 JSON Response with Cookie

How to set cookie using json response?

I noticed that for me, at least the following command is the only job 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 redirect target.

How can I translate this into ajax request and return json response with cookie?

+4
source share
2 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; } 
+3
source

Great hint!

A look at Symfony \ Component \ HttpFoundation \ ResponseHeaderBag also showed how to set headers for a json response for HTTP access control problems:

 $response->headers->set('Access-Control-Allow-Origin', '/* your subdomain */'); 
+1
source

All Articles