繁体   English   中英

Laravel中的数组细节错误

[英]Wrong array detail in laravel

我想将我的产品条件作为数组获取,以便将它们添加到购物车中,当我尝试将其添加到购物车中时,这是我产品的dd

array:6 [▼
  "id" => 4
  "name" => "product four"
  "price" => null
  "quantity" => "1"
  "attributes" => array:1 [▼
    "attr" => array:2 [▼
      "name" => "weight"
      "value" => "45"
    ]
  ]
  "conditions" => array:2 [▼
    0 => CartCondition {#685 ▼ // need to add this
      -args: array:4 [▼
        "name" => "Black"
        "value" => "10000"
        "type" => "additional"
        "target" => "item"
      ]
      -parsedRawValue: null
    }
    1 => CartCondition {#692 ▼ // need to add this
      -args: array:4 [▼
        "name" => "12 inch"
        "value" => "25000"
        "type" => "additional"
        "target" => "item"
      ]
      -parsedRawValue: null
    }
  ]
]

如您所见,与我的attributes不同,我的conditions不仅显示为数组,而且获取-args:-parsedRawValue: null

当我尝试在购物车中添加产品时,出现此错误:

Darryldecode \ Cart \ Exceptions \ InvalidItemException
validation.required

错误

这是我的功能(如何获取conditions以及在何处使用它们:

public function addingItem(Request $request, $id)
{
      //finding product
      $product = Product::findOrFail($id);
      //get product weight
      $weight = $product->weight;
      //list of discounts
      $discounts = Discount::all();
      //get current time
      $mytime = Carbon::now();

      // get product weight in cart as attribute
      $weightArray = [
        'attr' => [
              'name' => 'weight',
              'value' => $weight,
        ]
      ];


      $customAttributes = [];  // my conditions comes from here
      if(!empty($request->attr)){
          foreach($request->attr as $sub) {
          // find the suboption
              $sub = Suboption::find($sub);
              if (!empty($sub->id)) {
                  $itemCondition1 = new \Darryldecode\Cart\CartCondition(array(
                      'name' => $sub->title,
                      'value' => $sub->price,
                      'type' => 'additional',
                      'target' => 'item',
                  ));

                  array_push($customAttributes, $itemCondition1);
              }
          }
      }

      //adding product, options and conditions to cart
      Cart::add(array(
        'id' => $product->id,
        'name' => $product->title,
        'price' => $request->input('harga'),
        'quantity' => $request->input('quantity'),
        'attributes' => $weightArray,
        'conditions' => $customAttributes,  // added here
      ));
      Session::flash('success', 'This product added to your cart successfully.');
      return redirect()->back();
}

任何想法,为什么我会收到此错误以及如何解决?

如果要将集合转换为数组,请使用-> toarray()
另外,由于N + 1查询问题,您可能要考虑使用findMany()而不是find(),因此在foreach循环中运行查询也是一种不好的做法。
您也可能想阅读有关array_filter的信息

解决了

验证问题是由空的价格值引起的,这是因为我的前端循环获得了折扣时间和其他时间的不同价格,通过修复我的价格循环,我一直拥有我的产品价格,并且我的函数不再返回null 。

感谢您的帮助。

暂无
暂无

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

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