简体   繁体   English

创建购物车 - laravel 6

[英]create shopping cart - laravel 6

I want to create my own shopping cart我想创建自己的购物车

I would like to know what is the way to store various items and then show the items in the cart我想知道如何存储各种物品然后显示购物车中的物品

public function __construct()
{
    if(!\Session::has('cart')) \Session::put('cart', array());
}

my question is what code do I use to show the cart and then insert items inside it我的问题是我用什么代码来显示购物车然后在里面插入物品

While this is not a strictly Laravel solution , it is a relatively simple and well supported (browser compatible) way to store simple session data on the client side.虽然这不是一个严格的 Laravel 解决方案,但它是一种在客户端存储简单 session 数据的相对简单且支持良好(浏览器兼容)的方式。 I do this using sessionStorage.我使用 sessionStorage 来做到这一点。 Take a look at the sessionStorage documentation here .此处查看 sessionStorage 文档。

Example JS:示例 JS:

// Save data to sessionStorage
sessionStorage.setItem('cart', 'item_id');

// Get saved data from sessionStorage
let data = sessionStorage.getItem('cart');

// Remove saved data from sessionStorage
sessionStorage.removeItem('cart');

// Remove all saved data from sessionStorage
sessionStorage.clear();

A shopping cart would usually store several different items and while sessionStorage does not store arrays, the workaround is to convert the comma seperated string to an array using split(",") .购物车通常会存储几个不同的项目,而 sessionStorage 不存储 arrays,解决方法是使用split(",")将逗号分隔的字符串转换为数组。

Example:例子:

//if cart has value of 11,12,13,14,15
var ex1 = sessionStorage.getItem('cart').split(',');
//ex1 would be [11,12,13,14,15]

//without split(',')
var ex2 = sessionStorage.getItem('cart');
//ex2 would be 11,12,13,14,15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM