67 lines
1.9 KiB
PHP
67 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Author;
|
|
|
|
use Alert;
|
|
use App\Models\Post;
|
|
use App\Models\Category;
|
|
use App\Models\PostCategory; // Pastikan ini diimpor jika ada
|
|
use Illuminate\Http\Request;
|
|
use App\Http\Controllers\Controller;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use App\Http\Requests\PostRequest;
|
|
|
|
class PostController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
if (!Auth::check()) {
|
|
return redirect()->route('login')->with('error', 'You need to be logged in to view this page.');
|
|
}
|
|
|
|
$posts = Post::with('categories')
|
|
->where('user_id', Auth::user()->id)
|
|
->orderBy('created_at', 'desc')
|
|
->get();
|
|
|
|
$categories = Category::all();
|
|
return view('author.post', compact('posts', 'categories'));
|
|
}
|
|
|
|
public function store(PostRequest $request)
|
|
{
|
|
// dd($request->all());
|
|
$post = new Post();
|
|
$post->title = $request->title;
|
|
$post->description = $request->description;
|
|
$post->user_id = Auth::user()->id;
|
|
|
|
try {
|
|
|
|
$post->save();
|
|
foreach ($request->category_id as $item) {
|
|
$postCategory = new PostCategory();
|
|
$postCategory->post_id = $post->id;
|
|
$postCategory->category_id = $item;
|
|
$postCategory->save();
|
|
}
|
|
|
|
// // Simpan kategori jika ada
|
|
// if ($request->has('category_id') && is_array($request->category_id)) {
|
|
// $post->categories()->attach($request->category_id);
|
|
// }
|
|
|
|
|
|
// // Alert::success('Berhasil', 'Mengajukan Postingan');
|
|
return redirect()->back()->with('success', 'Postingan berhasil ditambahkan!');
|
|
} catch (\Exception $e) {
|
|
// Log kesalahan untuk debugging
|
|
// \Log::error('Error while saving post: ' . $e->getMessage());
|
|
|
|
// Alert::error('Gagal', 'Mengajukan Postingan');
|
|
return redirect()->back()->with('error', 'Gagal menambahkan postingan!');
|
|
}
|
|
}
|
|
|
|
}
|