KTV/app/Livewire/Admin/ArtistForm.php

115 lines
3.0 KiB
PHP

<?php
namespace App\Livewire\Admin;
use Livewire\Component;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use App\Models\Artist;
use App\Enums\ArtistCategory;
class ArtistForm extends Component
{
protected $listeners = ['openModal','closeModal', 'deleteArtist'];
public bool $canCreate;
public bool $canEdit;
public bool $canDelect;
public bool $showModal = false;
public ?int $artistId = null;
public array $categoryOptions =[];
public array $fields = [
'category' =>'unset',
'name' =>'',
'enable' => true,
];
public $selectedCategory = []; // 表單中選到的權限
public function mount()
{
$this->categoryOptions = collect(ArtistCategory::cases())->map(fn ($category) => [
'name' => $category->labels(),
'value' => $category->value,
])->toArray();
$this->canCreate = Auth::user()?->can('song-edit') ?? false;
$this->canEdit = Auth::user()?->can('song-edit') ?? false;
$this->canDelect = Auth::user()?->can('song-delete') ?? false;
}
public function openModal($id = null)
{
$this->resetFields();
if ($id) {
$artist = Artist::findOrFail($id);
$this->artistId = $artist->id;
$this->fields = $artist->only(array_keys($this->fields));
}
$this->showModal = true;
}
public function closeModal()
{
$this->resetFields();
$this->showModal = false;
}
public function save()
{
if ($this->artistId) {
if ($this->canEdit) {
$artist = Artist::findOrFail($this->artistId);
$artist->update($this->fields);
$this->dispatch('notify', [
'title' => '成功',
'description' => '歌手已更新',
'icon' => 'success',
]);
}
} else {
if ($canCreate) {
$artist = Artist::create($this->fields);
$this->dispatch('notify', [
'title' => '成功',
'description' => '歌手已新增',
'icon' => 'success',
]);
}
}
$this->resetFields();
$this->showModal = false;
$this->dispatch('pg:eventRefresh-artist-table');
}
public function deleteArtist($id)
{
if ($this->canDelect) {
Artist::findOrFail($id)->delete();
session()->flash('message', '歌手已刪除');
$this->dispatch('pg:eventRefresh-artist-table');
}
}
public function resetFields()
{
foreach ($this->fields as $key => $value) {
if ($key == 'category') {
$this->fields[$key] = 'unset';
} else {
$this->fields[$key] = '';
}
}
$this->artistId = null;
}
public function render()
{
return view('livewire.admin.artist-form');
}
}