Writeoff/Livewire/Product/ProductModal.php

95 lines
2.5 KiB
PHP
Raw Normal View History

2023-11-15 08:00:51 +00:00
<?php
namespace Modules\Writeoff\Livewire\Product;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Modules\Writeoff\Entities\Product;
use Modules\Writeoff\Http\Requests\Product\StoreProductRequest;
use Modules\Writeoff\Http\Requests\Product\UpdateProductRequest;
class ProductModal extends Component
{
public $id;
public $kode;
public $name;
public $edit_mode = false;
protected $listeners = [
'delete' => 'delete',
'update' => 'update',
];
public function render()
{
return view('writeoff::livewire.product.product-modal');
}
public function submit()
{
$this->validate();
// Validate the form input data
DB::transaction(function () {
// Prepare the data for creating a new user
$data = [
'kode' => $this->kode,
'name' => $this->name
];
if ($this->edit_mode) {
// Emit a success event with a message
$product = Product::find($this->id);
$product->update($data);
$this->dispatch('success', __('Product updated'));
} else {
// Emit a success event with a message
Product::create($data);
$this->dispatch('success', __('New Product created'));
}
});
// Reset the form fields after successful submission
$this->reset();
}
public function update($id)
{
$this->edit_mode = true;
$product = Product::find($id);
$this->id = $product->id;
$this->kode = $product->kode;
$this->name = $product->name;
}
public function delete($id)
{
Product::destroy($id);
// Emit a success event with a message
$this->dispatch('success', 'Product successfully deleted');
}
public function hydrate()
{
$this->resetErrorBag();
$this->resetValidation();
}
protected function rules()
{
if ($this->edit_mode) {
$request = new UpdateProductRequest();
} else {
$request = new StoreProductRequest();
}
return $request->rules();
}
}