user165222
user165222

Reputation: 173

Using Cookies in Laravel 4

How do you use cookies in Laravel 4?

I'm sure it's simple and something just isn't clicking with me but I need a little help.

As far as I can tell, you have to create a cookie like this:

$cookie = Cookie::make('test-cookie', 'test data', 30);

Then, aside from returning a custom response, how do you set it? What good is setting it with a custom response? When would I ever want to do this?

What if I want to set a cookie and return a view? What good does return Response::make('some text')->withCookie('test-cookie') actually do me aside from showing me how to use withCookie()?

Like I say, I'm probably just missing something here, but how would I use a cookie in a practical way...

...like somebody enters info, logs in, etc and I'd like to set a cookie and take them to a page made with a view?

Upvotes: 8

Views: 15433

Answers (4)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87789

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);

Upvotes: 5

Chris Goosey
Chris Goosey

Reputation: 498

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

Upvotes: 3

RiaanZA
RiaanZA

Reputation: 158

You can also attach cookies to redirects like this

return Redirect::route('home')->withCookie($cookie);

Upvotes: 1

Aken Roberts
Aken Roberts

Reputation: 13467

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.

Upvotes: 10

Related Questions