PostController.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\Post;
  4. use Illuminate\Http\Request;
  5. class PostController extends Controller
  6. {
  7. public function index()
  8. {
  9. $posts = Post::published()->latest('published_at')->paginate(10);
  10. return view('posts.index', compact('posts'));
  11. }
  12. public function show(Post $post)
  13. {
  14. if ($post->status !== 'published') {
  15. abort(404);
  16. }
  17. $comments = $post->comments()->approved()->latest()->get();
  18. return view('posts.show', compact('post', 'comments'));
  19. }
  20. public function create()
  21. {
  22. return view('posts.create');
  23. }
  24. public function store(Request $request)
  25. {
  26. $validated = $request->validate([
  27. 'title' => 'required|max:255',
  28. 'content' => 'required',
  29. 'status' => 'required|in:draft,published,scheduled',
  30. 'scheduled_at' => 'nullable|date|after:now',
  31. ]);
  32. $post = Post::create($validated);
  33. if ($validated['status'] === 'published') {
  34. $post->publish();
  35. } elseif ($validated['status'] === 'scheduled' && $validated['scheduled_at']) {
  36. $post->schedule($validated['scheduled_at']);
  37. }
  38. return redirect()->route('home', $post)
  39. ->with('success', 'Пост успешно создан');
  40. }
  41. public function edit(Post $post)
  42. {
  43. return view('posts.edit', compact('post'));
  44. }
  45. public function update(Request $request, Post $post)
  46. {
  47. $validated = $request->validate([
  48. 'title' => 'required|max:255',
  49. 'content' => 'required',
  50. 'status' => 'required|in:draft,published,scheduled',
  51. 'scheduled_at' => 'nullable|date|after:now',
  52. ]);
  53. $post->update($validated);
  54. if ($validated['status'] === 'published' && $post->status !== 'published') {
  55. $post->publish();
  56. } elseif ($validated['status'] === 'scheduled' && $validated['scheduled_at']) {
  57. $post->schedule($validated['scheduled_at']);
  58. }
  59. return redirect()->route('home', $post)
  60. ->with('success', 'Пост обновлен');
  61. }
  62. public function destroy(Post $post)
  63. {
  64. $post->delete();
  65. return redirect()->route('home')
  66. ->with('success', 'Пост удален');
  67. }
  68. }