簡體   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