78 lines
2.0 KiB
PHP
78 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Livewire\Admin;
|
|
|
|
use App\Models\News;
|
|
use App\Models\Category;
|
|
use Livewire\Component;
|
|
use Livewire\WithFileUploads;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Masmerise\Toaster\Toaster;
|
|
|
|
class NewsEdit extends Component
|
|
{
|
|
use WithFileUploads;
|
|
|
|
public News $news;
|
|
public $title, $category_id, $content, $oldImage;
|
|
public $is_published = false; // Default ke false
|
|
public $image;
|
|
|
|
public function mount(News $news)
|
|
{
|
|
$this->news = $news;
|
|
$this->title = $news->title;
|
|
$this->category_id = $news->category_id;
|
|
$this->content = $news->content;
|
|
|
|
// Memastikan tipe data boolean agar checkbox tercentang
|
|
$this->is_published = (bool) $news->is_published;
|
|
|
|
$this->oldImage = $news->image;
|
|
}
|
|
|
|
protected function rules()
|
|
{
|
|
return [
|
|
'title' => 'required|min:5|unique:news,title,' . $this->news->id,
|
|
'category_id' => 'required|exists:categories,id',
|
|
'image' => 'nullable|image|max:2048',
|
|
'content' => 'required|min:20',
|
|
'is_published' => 'boolean',
|
|
];
|
|
}
|
|
|
|
public function save()
|
|
{
|
|
$this->validate();
|
|
|
|
$data = [
|
|
'title' => $this->title,
|
|
'category_id' => $this->category_id,
|
|
'content' => $this->content,
|
|
'is_published' => $this->is_published,
|
|
];
|
|
|
|
if ($this->image) {
|
|
// Hapus gambar lama jika user upload gambar baru
|
|
if ($this->oldImage) {
|
|
Storage::disk('public')->delete($this->oldImage);
|
|
}
|
|
$data['image'] = $this->image->store('news', 'public');
|
|
}
|
|
|
|
$this->news->update($data);
|
|
|
|
Toaster::success('Berita berhasil diperbarui!');
|
|
|
|
return redirect()->route('admin.news');
|
|
}
|
|
|
|
public function render()
|
|
{
|
|
return view('livewire.admin.news.news-edit', [
|
|
'categories' => Category::all()
|
|
]);
|
|
}
|
|
}
|