104 lines
2.9 KiB
PHP
104 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Http\Requests\PostRequest;
|
|
use App\Models\Kategori;
|
|
use App\Models\Post;
|
|
use App\Models\SubKategori;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Inertia\Inertia;
|
|
|
|
class PostController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$posts = Post::with(['kategori', 'subkategori'])->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,
|
|
'subkategori' => $subkategori
|
|
]);
|
|
}
|
|
|
|
public function store(PostRequest $request)
|
|
{
|
|
|
|
try {
|
|
$data = $request->validated();
|
|
$data['IsPublish'] = $request->has('IsPublish');
|
|
|
|
if ($request->hasFile('ImagePost')) {
|
|
$data['ImagePost'] = $request->file('ImagePost')->store('images/posts');
|
|
}
|
|
|
|
Post::create($data);
|
|
|
|
return redirect()->route('admin.post.index')->with('success', 'Post berhasil ditambahkan');
|
|
} catch (\Exception $e) {
|
|
return redirect()->route('admin.post.index')->with('error', 'Post gagal ditambahkan');
|
|
}
|
|
|
|
}
|
|
|
|
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 = $request->validated();
|
|
|
|
if ($request->hasFile('ImagePost')) {
|
|
Storage::disk('public')->delete($post->ImagePost);
|
|
$data['ImagePost'] = $request->file('ImagePost')->store('images/posts', 'public');
|
|
}
|
|
|
|
$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', 'Something went wrong.');
|
|
}
|
|
}
|
|
|
|
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.');
|
|
}
|
|
}
|
|
|
|
|
|
}
|