我刚开始使用Cookie,而我无法理解如何在Laravel中访问Cookie。
背景:我正在尝试构建购物车。用户的订单详细信息存储在SQL中。如果用户是访客,我使用cookie(会话ID)来识别这些SQL行,如果用户已登录,则使用他们的用户ID。如果用户以访客身份开始然后登录,我想将此标识符从cookie(会话ID)更改为其用户ID。
问题:下面代码中的第二行(可实现上述操作)永远不会触发。我可以看到SQL行正在生成并且正在创建cookie,但Cookie :: get('id')似乎只返回null。如何在该行中获取Cookie值?
如果您需要更多详情,请告诉我。非常感谢提前!
代码(来自添加到购物车的控制器)
if (Auth::check()) {
if (Orders::where(['status' => 'cart', 'cookie_id' => Cookie::get('id')])->exists()) {
// Didn't include code here for simplicity. But code here never fires anyway
}
} else {
if (Cookie::get('id') == null) {
Cookie::queue('id', Session::getId(), 50000);
$cookie_id = Session::getId();
} else {
$cookie_id = Cookie::get('id');
Cookie::queue('id', Session::getId(), 50000);
}
// There is then code to identify the SQL row using the Cookie (session) ID. User ID is just set to 1 by default, where that user is not a real user (was just my way to get around foreign key requirement)
Orders::create(['session_id' => $_POST['sessions_id'], 'cookie_id' => $cookie_id, 'qty' => $_POST['nr_students'], 'order_id' => $o_id, 'status' => 'cart', 'user_id' => 1]);
答案 0 :(得分:0)
我建议你尝试使用add-to-cart方法Request
实例并从中获取cookie值。类似的东西:
public function addToCart(Request $request)
{
$myCookieValue = $request->cookie('cookie_name');
...
}