Using Cookies in Laravel 4

被刻印的时光 ゝ 提交于 2019-12-22 04:17:06

问题


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?


回答1:


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.




回答2:


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




回答3:


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



回答4:


You can also attach cookies to redirects like this

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


来源:https://stackoverflow.com/questions/18665751/using-cookies-in-laravel-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!