CommentController.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Http\Controllers\CustomArticle;
  3. use App\Http\Controllers\Core\Auth;
  4. use App\Http\Resources\CustomArticle\CommentCollection;
  5. use App\Http\Resources\CustomArticle\CommentResource;
  6. use App\Models\CustomArticle\Article;
  7. use App\Models\CustomArticle\Comment;
  8. use Illuminate\Http\Request;
  9. use App\Http\Controllers\Controller;
  10. class CommentController extends Controller
  11. {
  12. /**
  13. * 评论列表
  14. * @param Request $request
  15. * @param Article $article
  16. * @return CommentCollection
  17. */
  18. public function index(Request $request, Article $article)
  19. {
  20. $comments = $article->comments()->paginate($request->get('per_page', 20));
  21. foreach ($comments as $comment) {
  22. $comment->user;
  23. $comment->reply;
  24. }
  25. return new CommentCollection($comments);
  26. }
  27. /**
  28. * 评论详情
  29. * @param Article $article
  30. * @param Comment $comment
  31. * @return CommentResource
  32. */
  33. public function show(Article $article, Comment $comment)
  34. {
  35. $comment->user;
  36. $comment->reply;
  37. return new CommentResource($comment);
  38. }
  39. public function store(Request $request, Article $article, Comment $comment)
  40. {
  41. $this->validate($request, [
  42. 'content' => 'required|max:2',
  43. ]);
  44. $comment->article()->associate($article);
  45. $comment->uid = Auth::auth();
  46. $comment->save();
  47. return new CommentResource($comment);
  48. }
  49. /**
  50. * 删除评论
  51. * @param Article $article
  52. * @param Comment $comment
  53. * @return CommentResource
  54. * @throws \Illuminate\Auth\Access\AuthorizationException
  55. */
  56. public function destroy(Article $article, Comment $comment)
  57. {
  58. $this->authorize('delete', $comment);
  59. $comment->delete();
  60. return new CommentResource($comment);
  61. }
  62. }