111 lines
3.0 KiB
PHP
111 lines
3.0 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 Illuminate\Validation\Rule;
|
|
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 $outlet_ids = [];
|
|
|
|
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'],
|
|
'outlet_ids' => ['required', 'array', 'min:1'],
|
|
'outlet_ids.*' => Rule::exists('outlets', 'id'),
|
|
'image' => ['nullable', 'array'],
|
|
];
|
|
}
|
|
|
|
public function validationAttributes(): array
|
|
{
|
|
return [
|
|
'name' => 'nama',
|
|
'size' => 'ukuran',
|
|
'cost_price' => 'harga beli',
|
|
'sale_price' => 'harga jual',
|
|
'description' => 'deskripsi',
|
|
'outlet_ids' => 'outlet',
|
|
'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->outlet_ids = $this->bottle->outlets->pluck('id')->toArray();
|
|
$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,
|
|
]);
|
|
|
|
$bottle->outlets()->attach($this->outlet_ids);
|
|
|
|
$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->bottle->outlets()->attach($this->outlet_ids);
|
|
|
|
$this->syncMedia($this->image, $this->bottle, 'image');
|
|
$this->uploadMedia($this->image, $this->bottle, 'image');
|
|
});
|
|
}
|
|
}
|