From e98807da05abc369d2ace17b35ea45a60a06f43b Mon Sep 17 00:00:00 2001 From: Parsa Aghayi Date: Fri, 2 Oct 2026 11:06:06 -0400 Subject: [PATCH] Add post comments with moderation plus view/like interaction endpoints - blog_comments table + Comment model/factory; comments attach to the post, public list shows approved rows only, public submission starts unapproved - Admin moderation API: list/filter, approve, delete comments - Public POST posts/{slug}/view and posts/{slug}/like toggle counters - Route groups: comments throttled like the contact form, interactions at 60/min; comments resource exposed to the generic admin list --- .../Api/Admin/AdminResourceController.php | 3 + .../Api/Admin/CommentAdminController.php | 55 ++++++++ .../Api/Blog/CommentController.php | 60 +++++++++ .../Api/Blog/PostInteractionController.php | 56 ++++++++ app/Models/Blog/Comment.php | 41 ++++++ app/Models/Blog/Post.php | 6 + database/factories/Blog/CommentFactory.php | 26 ++++ ...0_02_130000_create_blog_comments_table.php | 34 +++++ routes/api.php | 27 ++++ tests/Feature/Blog/CommentTest.php | 127 ++++++++++++++++++ tests/Feature/Blog/PostInteractionTest.php | 62 +++++++++ 11 files changed, 497 insertions(+) create mode 100644 app/Http/Controllers/Api/Admin/CommentAdminController.php create mode 100644 app/Http/Controllers/Api/Blog/CommentController.php create mode 100644 app/Http/Controllers/Api/Blog/PostInteractionController.php create mode 100644 app/Models/Blog/Comment.php create mode 100644 database/factories/Blog/CommentFactory.php create mode 100644 database/migrations/2026_10_02_130000_create_blog_comments_table.php create mode 100644 tests/Feature/Blog/CommentTest.php create mode 100644 tests/Feature/Blog/PostInteractionTest.php diff --git a/app/Http/Controllers/Api/Admin/AdminResourceController.php b/app/Http/Controllers/Api/Admin/AdminResourceController.php index fe1dd7a..cdc30c2 100644 --- a/app/Http/Controllers/Api/Admin/AdminResourceController.php +++ b/app/Http/Controllers/Api/Admin/AdminResourceController.php @@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\Admin; use App\Http\Controllers\Controller; use App\Models\Blog\Category; +use App\Models\Blog\Comment; use App\Models\Blog\Post; use App\Models\Blog\Tag; use App\Models\Website\AboutMe; @@ -26,6 +27,7 @@ class AdminResourceController extends Controller 'projects' => Project::class, 'project-categories' => ProjectCategory::class, 'about-me' => AboutMe::class, + 'comments' => Comment::class, ]; /** @@ -39,6 +41,7 @@ class AdminResourceController extends Controller 'projects' => ['category'], 'skills' => ['aboutMe'], 'testimonials' => ['translations'], + 'comments' => ['post'], ]; /** diff --git a/app/Http/Controllers/Api/Admin/CommentAdminController.php b/app/Http/Controllers/Api/Admin/CommentAdminController.php new file mode 100644 index 0000000..f422699 --- /dev/null +++ b/app/Http/Controllers/Api/Admin/CommentAdminController.php @@ -0,0 +1,55 @@ +with('post:id,slug,title')->orderByDesc('id'); + + if ($request->has('approved')) { + $query->where('is_approved', $request->boolean('approved')); + } + + return response()->json(['data' => $query->get()]); + } + + /** + * Approve or reject a comment. + */ + public function update(Request $request, int $id): JsonResponse + { + $validated = $request->validate([ + 'is_approved' => ['required', 'boolean'], + ]); + + $comment = Comment::findOrFail($id); + $comment->is_approved = $validated['is_approved']; + $comment->save(); + + return response()->json(['data' => $comment]); + } + + /** + * Delete a comment. + */ + public function destroy(int $id): JsonResponse + { + Comment::findOrFail($id)->delete(); + + return response()->json(null, 200); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/Blog/CommentController.php b/app/Http/Controllers/Api/Blog/CommentController.php new file mode 100644 index 0000000..3fb5d78 --- /dev/null +++ b/app/Http/Controllers/Api/Blog/CommentController.php @@ -0,0 +1,60 @@ +firstOrFail(); + + $comments = $post->comments() + ->approved() + ->orderByDesc('created_at') + ->get(['id', 'name', 'body', 'created_at']); + + return response()->json([ + 'post_id' => $post->id, + 'comments' => $comments, + ]); + } + + /** + * Public comment submission. Every comment starts unapproved and appears + * only after an admin approves it, mirroring the contact form's moderation. + */ + public function store(Request $request, string $slug): JsonResponse + { + $post = Post::where('slug', $slug)->firstOrFail(); + + $validated = $request->validate([ + 'name' => ['required', 'string', 'max:120'], + 'email' => ['nullable', 'email', 'max:255'], + 'body' => ['required', 'string', 'min:3', 'max:2000'], + ]); + + $comment = $post->comments()->create([ + 'name' => $validated['name'], + 'email' => $validated['email'] ?? null, + 'body' => $validated['body'], + 'is_approved' => false, + ]); + + return response()->json([ + 'message' => 'دیدگاه شما ثبت شد و پس از تأیید نمایش داده می‌شود.', + 'comment' => $comment, + ], 201); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/Blog/PostInteractionController.php b/app/Http/Controllers/Api/Blog/PostInteractionController.php new file mode 100644 index 0000000..9049416 --- /dev/null +++ b/app/Http/Controllers/Api/Blog/PostInteractionController.php @@ -0,0 +1,56 @@ +firstOrFail(); + $post->increment('views'); + $post->refresh(); + + return response()->json([ + 'views' => $post->views, + 'likes' => $post->likes, + ]); + } + + /** + * Toggle a like. The frontend sends whether the visitor now likes the post; + * the counter grows on like and shrinks (never below zero) on unlike. + */ + public function like(Request $request, string $slug): JsonResponse + { + $validated = $request->validate([ + 'liked' => ['required', 'boolean'], + ]); + + $post = Post::where('slug', $slug)->firstOrFail(); + + if ($validated['liked']) { + $post->increment('likes'); + } elseif ($post->likes > 0) { + $post->decrement('likes'); + } + + $post->refresh(); + + return response()->json([ + 'views' => $post->views, + 'likes' => $post->likes, + ]); + } +} \ No newline at end of file diff --git a/app/Models/Blog/Comment.php b/app/Models/Blog/Comment.php new file mode 100644 index 0000000..8fec6bf --- /dev/null +++ b/app/Models/Blog/Comment.php @@ -0,0 +1,41 @@ + 'boolean', + ]; + } + + public function post() + { + return $this->belongsTo(Post::class); + } + + /** + * Only comments that survived moderation are shown to readers. + */ + public function scopeApproved($query) + { + return $query->where('is_approved', true); + } +} \ No newline at end of file diff --git a/app/Models/Blog/Post.php b/app/Models/Blog/Post.php index da36d79..ea2a018 100644 --- a/app/Models/Blog/Post.php +++ b/app/Models/Blog/Post.php @@ -49,6 +49,12 @@ class Post extends Model return $this->belongsToMany(Post::class, 'related_posts', 'post_id', 'related_post_id')->withTimestamps(); } + // دیدگاه‌های پست + public function comments() + { + return $this->hasMany(Comment::class); + } + // اسکوپ فیلتر public function scopeFilter($query, $filters) { diff --git a/database/factories/Blog/CommentFactory.php b/database/factories/Blog/CommentFactory.php new file mode 100644 index 0000000..9f6c99b --- /dev/null +++ b/database/factories/Blog/CommentFactory.php @@ -0,0 +1,26 @@ + + */ +class CommentFactory extends Factory +{ + protected $model = Comment::class; + + public function definition(): array + { + return [ + 'post_id' => Post::factory(), + 'name' => $this->faker->name(), + 'email' => $this->faker->safeEmail(), + 'body' => $this->faker->paragraph(), + 'is_approved' => false, + ]; + } +} \ No newline at end of file diff --git a/database/migrations/2026_10_02_130000_create_blog_comments_table.php b/database/migrations/2026_10_02_130000_create_blog_comments_table.php new file mode 100644 index 0000000..6a35e38 --- /dev/null +++ b/database/migrations/2026_10_02_130000_create_blog_comments_table.php @@ -0,0 +1,34 @@ +id(); + $table->unsignedBigInteger('post_id'); + $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); + $table->string('name', 120); + $table->string('email', 255)->nullable(); + $table->text('body'); + $table->boolean('is_approved')->default(false); + $table->timestamps(); + $table->index('post_id'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('blog_comments'); + } +}; \ No newline at end of file diff --git a/routes/api.php b/routes/api.php index 968bc58..3840aee 100644 --- a/routes/api.php +++ b/routes/api.php @@ -1,10 +1,13 @@ group(function () { Route::get('posts', [PostController::class, 'index']); Route::get('posts/{slug}', [PostController::class, 'show']); + Route::get('posts/{slug}/comments', [CommentController::class, 'index']); Route::get('categories', [CategoryController::class, 'index']); Route::get('categories/{id}', [CategoryController::class, 'show']); @@ -80,6 +84,25 @@ Route::middleware('throttle:60,1')->group(function () { Route::post('contact', [ContactMessageController::class, 'store']) ->middleware('throttle:5,1'); +/* +|-------------------------------------------------------------------------- +| Public blog interactions +|-------------------------------------------------------------------------- +| Anonymous but mutating, so each endpoint is throttled: comment submission +| is slow like the contact form, view/like counters are faster because they +| are single-column increments triggered once per page load. +*/ + +Route::middleware('throttle:60,1')->group(function () { + Route::prefix('blog')->group(function () { + Route::post('posts/{slug}/view', [PostInteractionController::class, 'view']); + Route::post('posts/{slug}/like', [PostInteractionController::class, 'like']); + }); +}); + +Route::post('blog/posts/{slug}/comments', [CommentController::class, 'store']) + ->middleware('throttle:5,1'); + /* |-------------------------------------------------------------------------- | Admin write API @@ -105,6 +128,10 @@ Route::middleware(['auth:sanctum', 'admin', 'throttle:30,1'])->group(function () Route::put('posts/{id}', [PostController::class, 'update']); Route::delete('posts/{id}', [PostController::class, 'destroy']); + Route::get('comments', [CommentAdminController::class, 'index']); + Route::put('comments/{id}', [CommentAdminController::class, 'update']); + Route::delete('comments/{id}', [CommentAdminController::class, 'destroy']); + Route::post('categories', [CategoryController::class, 'store']); Route::put('categories/{id}', [CategoryController::class, 'update']); Route::delete('categories/{id}', [CategoryController::class, 'destroy']); diff --git a/tests/Feature/Blog/CommentTest.php b/tests/Feature/Blog/CommentTest.php new file mode 100644 index 0000000..a29c233 --- /dev/null +++ b/tests/Feature/Blog/CommentTest.php @@ -0,0 +1,127 @@ +create(); + Comment::factory()->count(2)->for($post)->create(['is_approved' => true]); + Comment::factory()->for($post)->create(['is_approved' => false]); + + $response = $this->getJson("/api/blog/posts/{$post->slug}/comments"); + + $response->assertStatus(200) + ->assertJsonCount(2, 'comments') + ->assertJsonPath('post_id', $post->id); + } + + public function test_public_comments_are_created_pending() + { + $post = Post::factory()->create(); + + $response = $this->postJson("/api/blog/posts/{$post->slug}/comments", [ + 'name' => 'Reader', + 'email' => 'reader@example.com', + 'body' => 'A thoughtful comment.', + ]); + + $response->assertStatus(201) + ->assertJsonPath('comment.name', 'Reader'); + + $this->assertDatabaseHas('blog_comments', [ + 'post_id' => $post->id, + 'name' => 'Reader', + 'email' => 'reader@example.com', + 'body' => 'A thoughtful comment.', + 'is_approved' => false, + ]); + } + + public function test_comment_submission_validates_required_fields() + { + $post = Post::factory()->create(); + + $this->postJson("/api/blog/posts/{$post->slug}/comments", [ + 'name' => '', + 'body' => '', + ])->assertStatus(422); + + $this->postJson("/api/blog/posts/{$post->slug}/comments", [ + 'name' => 'Reader', + 'email' => 'not-an-email', + 'body' => 'ok', + ])->assertStatus(422); + } + + public function test_comment_endpoints_404_on_unknown_posts() + { + $this->getJson('/api/blog/posts/does-not-exist/comments')->assertStatus(404); + $this->postJson('/api/blog/posts/does-not-exist/comments', [ + 'name' => 'A', + 'body' => 'B', + ])->assertStatus(404); + } + + public function test_admin_can_list_and_filter_comments() + { + $this->actingAsAdmin(); + $post = Post::factory()->create(); + Comment::factory()->for($post)->create(['is_approved' => true]); + Comment::factory()->for($post)->create(['is_approved' => false]); + + $this->getJson('/api/blog/comments') + ->assertStatus(200) + ->assertJsonCount(2, 'data'); + + $this->getJson('/api/blog/comments?approved=1') + ->assertStatus(200) + ->assertJsonCount(1, 'data'); + } + + public function test_admin_can_approve_then_the_comment_becomes_public() + { + $this->actingAsAdmin(); + $post = Post::factory()->create(); + $comment = Comment::factory()->for($post)->create(['is_approved' => false]); + + $this->getJson("/api/blog/posts/{$post->slug}/comments") + ->assertJsonCount(0, 'comments'); + + $this->putJson("/api/blog/comments/{$comment->id}", ['is_approved' => true]) + ->assertStatus(200) + ->assertJsonPath('data.is_approved', true); + + $this->getJson("/api/blog/posts/{$post->slug}/comments") + ->assertJsonCount(1, 'comments'); + } + + public function test_admin_can_delete_a_comment() + { + $this->actingAsAdmin(); + $post = Post::factory()->create(); + $comment = Comment::factory()->for($post)->create(); + + $this->deleteJson("/api/blog/comments/{$comment->id}")->assertStatus(200); + + $this->assertDatabaseMissing('blog_comments', ['id' => $comment->id]); + } + + public function test_moderation_requires_an_admin() + { + $comment = Comment::factory()->create(); + + $this->getJson('/api/blog/comments')->assertUnauthorized(); + $this->putJson("/api/blog/comments/{$comment->id}", ['is_approved' => true]) + ->assertUnauthorized(); + $this->deleteJson("/api/blog/comments/{$comment->id}")->assertUnauthorized(); + } +} \ No newline at end of file diff --git a/tests/Feature/Blog/PostInteractionTest.php b/tests/Feature/Blog/PostInteractionTest.php new file mode 100644 index 0000000..79a1727 --- /dev/null +++ b/tests/Feature/Blog/PostInteractionTest.php @@ -0,0 +1,62 @@ +create(['views' => 5, 'likes' => 2]); + + $response = $this->postJson("/api/blog/posts/{$post->slug}/view"); + + $response->assertStatus(200) + ->assertJsonPath('views', 6) + ->assertJsonPath('likes', 2); + + $this->assertDatabaseHas('posts', ['id' => $post->id, 'views' => 6]); + } + + public function test_like_toggles_the_counter() + { + $post = Post::factory()->create(['views' => 0, 'likes' => 3]); + + $this->postJson("/api/blog/posts/{$post->slug}/like", ['liked' => true]) + ->assertStatus(200) + ->assertJsonPath('likes', 4); + + $this->postJson("/api/blog/posts/{$post->slug}/like", ['liked' => false]) + ->assertStatus(200) + ->assertJsonPath('likes', 3); + } + + public function test_unlike_never_drives_likes_below_zero() + { + $post = Post::factory()->create(['likes' => 0]); + + $this->postJson("/api/blog/posts/{$post->slug}/like", ['liked' => false]) + ->assertStatus(200) + ->assertJsonPath('likes', 0); + } + + public function test_like_requires_the_liked_flag() + { + $post = Post::factory()->create(); + + $this->postJson("/api/blog/posts/{$post->slug}/like", []) + ->assertStatus(422); + } + + public function test_interactions_404_on_unknown_posts() + { + $this->postJson('/api/blog/posts/does-not-exist/view')->assertStatus(404); + $this->postJson('/api/blog/posts/does-not-exist/like', ['liked' => true])->assertStatus(404); + } +} \ No newline at end of file