PostController.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Str;
  6. use App\Models\Post;
  7. class PostController extends Controller
  8. {
  9. /**
  10. * Display a listing of the resource.
  11. */
  12. public function index()
  13. {
  14. //
  15. $posts = Post::latest()->paginate(10);
  16. return view('admin.posts.index', compact('posts'));
  17. }
  18. /**
  19. * Show the form for creating a new resource.
  20. */
  21. public function create()
  22. {
  23. //
  24. return view('admin.posts.form');
  25. }
  26. /**
  27. * Store a newly created resource in storage.
  28. */
  29. public function store(Request $request)
  30. {
  31. //
  32. $validated = $request->validate([
  33. 'title' => 'required|string',
  34. 'content' => 'required|string',
  35. ]);
  36. $post = Post::create([
  37. 'title' => $validated['title'],
  38. 'slug' => Str::slug($validated['title']),
  39. 'content' => $validated['content'],
  40. 'is_published' => $request->boolean('is_published'),
  41. 'published_at' => $request->boolean('is_published') ? now() : null,
  42. 'user_id' => auth()->id(),
  43. 'scheduled_at' => $request->filled('scheduled_at') ? $request->input('scheduled_at') : null,
  44. ]);
  45. return redirect()->route('admin.posts.index')->with('success', 'Пост успешно создан!');
  46. }
  47. /**
  48. * Display the specified resource.
  49. */
  50. public function show(string $id)
  51. {
  52. //
  53. }
  54. /**
  55. * Show the form for editing the specified resource.
  56. */
  57. public function edit(Post $post)
  58. {
  59. //
  60. return view('admin.posts.form', compact('post'));
  61. }
  62. /**
  63. * Update the specified resource in storage.
  64. */
  65. public function update(Request $request, Post $post)
  66. {
  67. //
  68. $validated = $request->validate([
  69. 'title' => 'required|string',
  70. 'content' => 'required|string',
  71. ]);
  72. $post->update([
  73. 'title' => $validated['title'],
  74. 'content' => $validated['content'],
  75. 'is_published' => $request->boolean('is_published'),
  76. 'published_at' => $request->boolean('is_published') ? now() : null,
  77. 'scheduled_at' => $request->filled('scheduled_at') ? $request->input('scheduled_at') : null,
  78. ]);
  79. return redirect()->route('admin.posts.index')->with('success', 'Пост успешно изменен!');
  80. }
  81. /**
  82. * Remove the specified resource from storage.
  83. */
  84. public function destroy(Post $post)
  85. {
  86. //
  87. $post->delete();
  88. return redirect()->route('admin.posts.index')->with('success', 'Пост успешно удален!');
  89. }
  90. }