parfum/app/Livewire/Forms/ExpenseForm.php

80 lines
1.8 KiB
PHP

<?php
namespace App\Livewire\Forms;
use App\Models\Expense;
use App\Rules\UnsignedInteger;
use App\Traits\WithMediaHandler;
use Illuminate\Support\Facades\DB;
use Livewire\Form;
class ExpenseForm extends Form
{
use WithMediaHandler;
public ?Expense $expense = null;
public string $description = '';
public string $amount = '';
public array $image = [];
public function rules(): array
{
return [
'description' => ['required', 'string', 'max:100'],
'amount' => ['required', 'numeric', new UnsignedInteger],
'image' => ['nullable', 'array'],
];
}
public function validationAttributes(): array
{
return [
'description' => 'keterangan',
'amount' => 'jumlah',
'image' => 'gambar',
];
}
public function setExpense(Expense $expense)
{
$this->expense = $expense;
$this->description = $expense->description;
$this->amount = $expense->amount;
$this->image = $this->mapMediaCollection($expense->getMedia('image'));
}
public function store()
{
$this->validate();
DB::transaction(function () {
$expense = Expense::create([
'description' => $this->description,
'amount' => $this->amount,
]);
$this->uploadMedia($this->image, $expense, 'image');
});
}
public function update()
{
$this->validate();
DB::transaction(function () {
$this->expense->update([
'description' => $this->description,
'amount' => $this->amount,
]);
$this->syncMedia($this->image, $this->expense, 'image');
$this->uploadMedia($this->image, $this->expense, 'image');
});
}
}