问题描述
我正在为某些点击事件设置Cookie.然后在将值存储在Cookie中后,我要
I'm setting cookie on some click event. Then after storing value in cookie, I want to
- 检查cookie是否存在
- 获取cookie值
我已经通过引用Laravel官方文档开发了一个功能.控制台显示已设置cookie.但是在那之后,我无法解决视图(刀片模板)的两点(在上面的列表中提到).它始终显示(Cookie::get('cookie.clients'))
'null'.但是浏览器控制台会显示该Cookie.如果有人知道答案,将不胜感激.
I have developed a function by referring Laravel official docs. Console shows that cookies have been set. But after that, I can not solve two point (mentioned in above list) for view(Blade Template). It always shows (Cookie::get('cookie.clients'))
'null'. But browser console displays that cookie.If anyone knows answer, it will be appreciated.
这是我的代码.
控制器
use App\Client;
use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Controller;
use App\Repositories\ClientRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
class ClientController extends Controller
{
public function cookieadd(Request $request, Client $client)
{
$clients = [];
if (Cookie::get('cookie.clients') != null)
{
$clients = Cookie::get('cookie.clients');
}
array_push($clients, $client);
Cookie::forever('cookie.clients', $clients);
return redirect('/client');
}
}
查看
@if (Cookie::get('cookie.clients') != null)
<p>cookie is set</p>
@else
<p>cookie isn't set</p>
@endif
推荐答案
您正在创建一个cookie对象,但没有将其与响应一起发送.
You're creating a cookie object but you're not sending it with the response.
您可以将其直接添加到控制器中的响应中
You can either, add it directly to your response in a controller
$cookie = Cookie::forever('cookie.clients', $clients);
return redirect('/client')->withCookie($cookie);
或者您可以将Cookie排队并使用 AddQueuedCookiesToResponse 将其自动添加到响应的中间件.
Or you can queue a cookie and use the AddQueuedCookiesToResponse Middleware to automatically add it to the Response.
Cookie::queue(Cookie::forever('cookie.clients', $clients));
return redirect('/client');
这篇关于如何在Laravel 5.2中使用Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!