si-klinik/sk-klinik.my.id/app/Livewire/Admin/ServiceManager.php

137 lines
3.5 KiB
PHP

<?php
namespace App\Livewire\Admin;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\Service;
use App\Models\ServiceCategory;
use Masmerise\Toaster\Toaster;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Storage;
class ServiceManager extends Component
{
use WithPagination, WithFileUploads;
public $search = '';
public $filterCategory = '';
public $serviceId;
public $name, $category_id, $description;
public $isModalOpen = false;
public $photos = []; // Untuk menampung file baru yang diupload
public $existingPhotos = []; // Untuk menampilkan foto yang sudah ada saat edit
public function updatedSearch()
{
$this->resetPage();
}
public function updatedFilterCategory()
{
$this->resetPage();
}
public function create()
{
$this->resetForm();
$this->isModalOpen = true;
}
public function edit($id)
{
$service = Service::findOrFail($id);
$this->serviceId = $service->id;
$this->name = $service->name;
$this->category_id = $service->category_id;
$this->description = $service->description;
$this->existingPhotos = $service->photo ?? []; // Tampilkan foto yang sudah ada
$this->isModalOpen = true;
}
public function save()
{
$this->validate([
'name' => 'required',
'category_id' => 'required',
'photos.*' => 'image|max:2048', // Validasi tiap file (max 2MB)
]);
$paths = $this->existingPhotos;
if ($this->photos) {
if (!Storage::disk('public')->exists('services')) {
Storage::disk('public')->makeDirectory('services');
}
foreach ($this->photos as $photo) {
$paths[] = $photo->store('services', 'public');
}
}
Service::updateOrCreate(
['id' => $this->serviceId],
[
'name' => $this->name,
'category_id' => $this->category_id,
'description' => $this->description,
'photo' => $paths,
]
);
$this->isModalOpen = false;
$this->resetForm();
Toaster::success('Data layanan berhasil disimpan.');
}
public function removePhoto($index)
{
unset($this->existingPhotos[$index]);
$this->existingPhotos = array_values($this->existingPhotos);
}
public function delete($id)
{
$service = Service::findOrFail($id);
if ($service->photo) {
foreach ($service->photo as $path) {
Storage::disk('public')->delete($path);
}
}
$service->delete();
Toaster::success('Data layanan berhasil dihapus.');
}
private function resetForm()
{
$this->serviceId = null;
$this->name = '';
$this->category_id = '';
$this->description = '';
$this->photos = []; // Reset input file
$this->existingPhotos = []; // Reset foto yang sudah ada
}
public function render()
{
$query = Service::with('category');
if ($this->search) {
$query->where('name', 'like', "%{$this->search}%");
}
if ($this->filterCategory) {
$query->where('category_id', $this->filterCategory);
}
return view('livewire.admin.service-manager', [
'services' => $query->latest()->paginate(10),
'categories' => ServiceCategory::pluck('name', 'id')
]);
}
}