Writeoff/Livewire/Branch/BranchModal.php

95 lines
2.5 KiB
PHP
Raw Normal View History

2023-10-05 15:32:26 +00:00
<?php
namespace Modules\Writeoff\Livewire\Branch;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Modules\Writeoff\Entities\Branch;
2023-10-09 11:12:51 +00:00
use Modules\Writeoff\Http\Requests\Branch\StoreBranchRequest;
use Modules\Writeoff\Http\Requests\Branch\UpdateBranchRequest;
2023-10-05 15:32:26 +00:00
class BranchModal extends Component
{
2023-10-09 11:12:51 +00:00
public $id;
2023-10-05 15:32:26 +00:00
public $kode;
public $name;
public $edit_mode = false;
protected $listeners = [
'delete_branch' => 'deleteBranch',
'update_branch' => 'updateBranch',
];
public function render()
{
return view('writeoff::livewire.branch.branch-modal');
}
2023-10-09 11:12:51 +00:00
protected function rules()
{
if ($this->edit_mode) {
$request = new UpdateBranchRequest();
} else {
$request = new StoreBranchRequest();
}
return $request->rules();
}
2023-10-05 15:32:26 +00:00
public function submit()
{
$this->validate();
2023-10-09 11:12:51 +00:00
// Validate the form input data
2023-10-05 15:32:26 +00:00
DB::transaction(function () {
// Prepare the data for creating a new user
$data = [
'name' => $this->name,
];
// Create a new user record in the database
$user = Branch::updateOrCreate([
'kode' => $this->kode,
], $data);
if ($this->edit_mode) {
// Emit a success event with a message
$this->dispatch('success', __('Branch updated'));
} else {
// Emit a success event with a message
$this->dispatch('success', __('New Branch created'));
}
});
// Reset the form fields after successful submission
$this->reset();
}
public function deleteBranch($id)
{
Branch::destroy($id);
// Emit a success event with a message
$this->dispatch('success', 'Branch successfully deleted');
}
public function updateBranch($id)
{
$this->edit_mode = true;
$branch = Branch::find($id);
2023-10-09 11:12:51 +00:00
$this->id = $branch->id;
2023-10-05 15:32:26 +00:00
$this->kode = $branch->kode;
$this->name = $branch->name;
}
public function hydrate()
{
$this->resetErrorBag();
$this->resetValidation();
}
}