Using Cookies in Laravel 4 Using Cookies in Laravel 4 laravel laravel

Using Cookies in Laravel 4


To return a cookie with a view, you should add your view to a Response object, and return the whole thing. For example:

$view = View::make('categories.list')->with('categories', $categories);$cookie = Cookie::make('test-cookie', 'test data', 30);return Response::make($view)->withCookie($cookie);

Yeah, it's a little bit more to write. The reasoning is that Views and a Response are two separate things. You can use Views to parse content and data for various uses, not necessarily for sending to the browser. That's what Response is for, and why if you want to set headers, cookies, or things of that nature, it is done via the Response object.


This one is what I prefer to use: at any time, you can queue a cookie to be sent in the next request

Cookie::queue('cookieName', 'cookieValue', $lifeTimeInMinutes);


As described in the other answers, you can attach Cookies to Response/Views/Redirects simply enough.

$cookie = Cookie::make('name', 'value', 60);$response = Response::make('Hello World');return $response->withCookie($cookie);

or

$cookie = Cookie::make('name', 'value', 60);$view = View::make('categories.list');return Response::make($view)->withCookie($cookie);

or

$cookie = Cookie::make('name', 'value', 60);return Redirect::route('home')->withCookie($cookie);

But you don't need to attach your Cookie to your response. Using Cookie:queue(), in the same way you would use Cookie::make(), your cookie will be included with the response when it is sent. No extra withCookie() method is needed.

Source: http://laravel.com/docs/requests#cookies