parfum/app/Livewire/Forms/BottleForm.php
Yoga Pangestu 4c43729299 feat(bottle): crud botol
-menambahkan skema model dan migrsai
-menyesuaikan relasi
2025-10-02 09:34:56 +07:00

101 lines
2.6 KiB
PHP

<?php
namespace App\Livewire\Forms;
use App\Models\Bottle;
use App\Rules\UnsignedInteger;
use App\Traits\WithMediaHandler;
use Illuminate\Support\Facades\DB;
use Livewire\Form;
class BottleForm extends Form
{
use WithMediaHandler;
public ?Bottle $bottle = null;
public string $name = '';
public string $size = '';
public string $cost_price = '';
public string $sale_price = '';
public ?string $description = null;
public array $image = [];
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:50'],
'size' => ['required', 'numeric', new UnsignedInteger],
'cost_price' => ['required', 'numeric', new UnsignedInteger],
'sale_price' => ['required', 'numeric', new UnsignedInteger],
'description' => ['nullable', 'string'],
'image' => ['nullable', 'array'],
];
}
public function validationAttributes(): array
{
return [
'name' => 'nama',
'size' => 'ukuran',
'cost_price' => 'harga beli',
'sale_price' => 'harga jual',
'description' => 'deskripsi',
'image' => 'gambar',
];
}
public function setBottle(Bottle $bottle)
{
$this->bottle = $bottle;
$this->name = $bottle->name;
$this->size = $bottle->size;
$this->cost_price = $bottle->cost_price;
$this->sale_price = $bottle->sale_price;
$this->description = $bottle->description;
$this->image = $this->mapMediaCollection($bottle->getMedia('image'));
}
public function store()
{
$this->validate();
DB::transaction(function () {
$bottle = Bottle::create([
'name' => $this->name,
'size' => $this->size,
'cost_price' => $this->cost_price,
'sale_price' => $this->sale_price,
'description' => $this->description,
]);
$this->uploadMedia($this->image, $bottle, 'image');
});
}
public function update()
{
$this->validate();
DB::transaction(function () {
$this->bottle->update([
'name' => $this->name,
'size' => $this->size,
'cost_price' => $this->cost_price,
'sale_price' => $this->sale_price,
'description' => $this->description,
]);
$this->syncMedia($this->image, $this->bottle, 'image');
$this->uploadMedia($this->image, $this->bottle, 'image');
});
}
}