I put all the unset items in a variable so that I can delete in store function. But I got an error Attempt to read property "pr_id" on array I already cast an object on my remove function
public $selectedDeletedProducts = [];
public function removeProduct($index)
{
if (isset($this->orderProducts[$index])) {
$removedProduct = $this->orderProducts[$index];
$this->selectedDeletedProducts[] = (object) $removedProduct;
unset($this->orderProducts[$index]);
$this->orderProducts = array_values($this->orderProducts);
$this->updatedorderProducts();
}
}
//store
public function store()
{
$this->prefix_id = 1;
$this->user_id = Auth::user()->id;
$this->pr_status_id = 1;
$data = $this->validate([
'pr_date' => 'required',
'number' => 'required',
'prefix_id' => 'required',
'pr_no' => 'required',
'supplier_id' => 'required',
'user_id' => 'required',
'remarks' => 'nullable',
'pr_status_id' => 'required'
]);
if ($this->purchaseRequestId) {
$updatePurchaseRequest = PurchaseRequest::whereId($this->purchaseRequestId)->first();
$updatePurchaseRequest->update($data);
foreach ($this->orderProducts as $key => $value) {
$unitTypeId = $value['unit_type_id'] ?? 1;
PurchaseRequestItems::updateOrCreate(
[
'pr_id' => $this->purchaseRequestId,
'stock_management_id' => $value['stock_management_id'],
],
[
'unit_type_id' => $unitTypeId,
'qty' => $value['qty'],
'price' => $value['price'],
'sub_total_price' => (int) $value['sub_total_price'],
'post_status_id' => 1,
]
);
}
$action = 'edit';
$message = 'Purchase Request Record Successfully Updated';
} else {
$purchareRequest = PurchaseRequest::create($data);
foreach ($this->orderProducts as $key => $value) {
$unitTypeId = $value['unit_type_id'] ?? 1;
PurchaseRequestItems::create([
'pr_id' => $purchareRequest->id,
'stock_management_id' => $value['stock_management_id'],
'unit_type_id' => $unitTypeId,
'qty' => $value['qty'],
'price' => $value['price'],
'sub_total_price' => (int) $value['sub_total_price'],
'post_status_id' => 1,
]);
}
$action = 'store';
$message = 'Purchase Request Record Successfully Created';
}
//delete items
foreach ($this->selectedDeletedProducts as $index => $selectedRemoveProduct) {
//The error is here in the delete
$deleteItem = PurchaseRequestItems::where('pr_id', $selectedRemoveProduct->pr_id)
->where('stock_management_id', $selectedRemoveProduct->stock_management_id)
->first();
if ($deleteItem) {
$deleteItem->delete();
}
unset($this->selectedDeletedProducts[$index]);
}
$this->resetInputFields();
$this->emit('refreshPurchaseRequest');
$this->emit('closePurchaseRequesthModal');
$this->emit('showEmitedFlashMessage', $action, $message);
}