latest()->get(); $kategori = Kategori::all(); $subkategori = SubKategori::all(); return Inertia::render('admin/post/index_post', [ 'posts' => $posts, 'kategori' => $kategori, 'subkategori' => $subkategori ]); } public function create() { $kategori = Kategori::all(); $subkategori = SubKategori::all(); return Inertia::render('admin/post/add_post', [ 'kategori' => Kategori::all(), 'subkategori' => SubKategori::all(), 'existingPosts' => Post::select('JudulPost', 'KategoriId')->get() ]); } public function store(PostRequest $request) { try { $data = $request->validated(); DB::beginTransaction(); try { $data['IsPublish'] = $request->boolean('IsPublish'); if ($request->hasFile('ImagePost')) { $file = $request->file('ImagePost'); if (!$file->isValid()) { throw new \Exception('Invalid image file'); } $data['ImagePost'] = $file->store('images/posts', 'public'); if ($data['ImagePost'] === false) { throw new \Exception('Failed to store image'); } } $post = Post::create($data); DB::commit(); return redirect() ->route('admin.post.index') ->with('success', 'Post berhasil ditambahkan'); } catch (\Exception $e) { DB::rollBack(); if (isset($data['ImagePost']) && Storage::disk('public')->exists($data['ImagePost'])) { Storage::disk('public')->delete($data['ImagePost']); } Log::error('Error creating post: ' . $e->getMessage()); return redirect() ->route('admin.post.index') ->with('error', 'Post gagal ditambahkan: ' . $e->getMessage()); } } catch (\Exception $e) { Log::error('Validation error: ' . $e->getMessage()); return redirect() ->route('admin.post.index') ->with('error', 'Validasi gagal: ' . $e->getMessage()); } } public function edit(Post $post) { return Inertia::render('admin/post/edit_post', [ 'post' => $post, 'kategori' => Kategori::all(), 'subkategori' => SubKategori::where('KategoriId', $post->KategoriId)->get(), ]); } public function update(PostRequest $request, Post $post) { try { $data = array_filter($request->validated(), function($value) { return $value !== null; }); if ($request->hasFile('ImagePost')) { if ($post->ImagePost && Storage::disk('public')->exists($post->ImagePost)) { Storage::disk('public')->delete($post->ImagePost); } $data['ImagePost'] = $request->file('ImagePost')->store('images/posts', 'public'); } if (isset($data['IsPublish'])) { $data['IsPublish'] = (bool) $data['IsPublish']; } $post->update($data); return redirect() ->route('admin.post.index') ->with('success', 'Post berhasil diperbarui.'); } catch (\Exception $e) { Log::error('Error updating Post: ' . $e->getMessage()); return back()->with('error', 'Terjadi kesalahan saat memperbarui post.'); } } public function destroy(Post $post) { try { Storage::disk('public')->delete($post->ImagePost); $post->delete(); return redirect()->route('admin.post.index')->with('success', 'Post berhasil dihapus.'); } catch (\Exception $e) { Log::error('Error deleting Post: ' . $e->getMessage()); return back()->with('error', 'Something went wrong.'); } } }