66 lines
No EOL
1.7 KiB
PHP
66 lines
No EOL
1.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\Post;
|
|
use App\Models\Comment;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
|
|
class CommentController extends Controller
|
|
{
|
|
public function index(Post $post): JsonResponse
|
|
{
|
|
$comments = $post->comments()
|
|
->with('author:id,name')
|
|
->get()
|
|
->map(fn($comment) => [
|
|
'id' => $comment->id,
|
|
'content' => $comment->content,
|
|
'author' => $comment->author,
|
|
'created_at' => $comment->created_at,
|
|
]);
|
|
|
|
return response()->json([
|
|
'comments' => $comments
|
|
]);
|
|
}
|
|
|
|
public function store(Request $request, Post $post): JsonResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'content' => 'required|string',
|
|
]);
|
|
|
|
$comment = $post->comments()->create([
|
|
...$validated,
|
|
'author_id' => $request->user()->id,
|
|
]);
|
|
|
|
$comment->load('author:id,name');
|
|
|
|
return response()->json([
|
|
'message' => 'Comment added successfully',
|
|
'comment' => [
|
|
'id' => $comment->id,
|
|
'content' => $comment->content,
|
|
'author' => $comment->author,
|
|
'created_at' => $comment->created_at,
|
|
]
|
|
]);
|
|
}
|
|
|
|
public function destroy(Comment $comment): JsonResponse
|
|
{
|
|
$this->authorize('delete', $comment);
|
|
|
|
$comment->delete();
|
|
|
|
return response()->json([
|
|
'message' => 'Comment deleted successfully'
|
|
]);
|
|
}
|
|
}
|