PHP shopping cart with laravel – quantity issue
我正在处理一个 laravel 购物网站项目,但我对购物车中产品的数量有疑问。
我对 Laravel 比较陌生,所以事情对我来说变得更加复杂……
问题是我不能真正以有效的方式循环(并寻找)类似的产品。
但是当我按下”加入购物车”-按钮时,这个函数会运行:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public function cart(Product $product){
$cart = session()->get(‘cart’); // If Cart is empty, add a new array in the session $array_cart = json_decode($cart[$i], true); return back(); |
产品是对象,我不确定如何循环查找产品的 id 以匹配数组产品 id。我尝试使用 json_decode() 来查看它是否会变成一个数组,但我在这里可能是错的,因为当我返回值时它是相同的 “object”。例如,购物车中的单个产品可能如下所示:
1
2 3 4 5 6 7 8 9 |
[{“id”: 4,
“name”:“HP Desktop”, “description”:“Ordinary desktop”, “category”:“Desktop”, “price”: 1, “views”: 63, “created_at”:“2016-04-11 14:42:58”, “updated_at”:“2016-05-27 09:12:59” }] |
你需要运行一个 foreach 循环,这将遍历所有对象。
例如,您可以在 controller 中运行此代码以获取 id:
1
2 3 |
foreach($products as $product) {
dump($product->id); } |
或者你可以在 blade view.
中使用它
1
2 3 |
@foreach($products as $product)
dump($product->id); @endforeach |
我建议您在对象中添加一个 quantity,然后您可以更新 quantity 并计算价格。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public function cart(Product $product){
$cart = session()->get(‘cart’); // If Cart is empty, add a new array in the session if($found !== true) { return back(); |
希望这行得通!
- 我非常感谢你!我想投票,但我需要 15 声望。但再次感谢! :)
- 没问题的小伙伴!也许你在几天内就有 15 名声望(还有 2 名)!为它工作!
- 但实际上我遇到了一个小问题。出现错误”未定义的变量 $found”,我尝试自己修复它,但没有技能去做。
- 如果你使用 if(!isset($found)
来源:https://www.codenong.com/37480817/