Add post comments with moderation plus view/like interaction endpoints
Deploy Backend / deploy (push) Successful in 2m41s
Deploy Backend / deploy (push) Successful in 2m41s
- 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
This commit is contained in:
1 parent
fbacb0c9a1
commit
e98807da05
11 files changed
+497
No files matched your search
@@ -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'],
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Blog\Comment;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* Moderation endpoints for reader comments. Public comments are never shown
|
||||
* until an admin approves them here; pending rows are the inbox.
|
||||
*/
|
||||
class CommentAdminController extends Controller
|
||||
{
|
||||
/**
|
||||
* List comments, newest first. `?approved=1|0` filters by moderation state.
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$query = Comment::query()->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Blog;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Blog\Comment;
|
||||
use App\Models\Blog\Post;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* @OA\Tag(name="Post comments", description="Reader comments on blog posts")
|
||||
*/
|
||||
class CommentController extends Controller
|
||||
{
|
||||
/**
|
||||
* Public list of approved comments for a post, newest first.
|
||||
*/
|
||||
public function index(string $slug): JsonResponse
|
||||
{
|
||||
$post = Post::where('slug', $slug)->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Blog;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Blog\Post;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* @OA\Tag(name="Post interactions", description="Anonymous view and like counters")
|
||||
*/
|
||||
class PostInteractionController extends Controller
|
||||
{
|
||||
/**
|
||||
* Count a view. The caller records one hit per session on its side, so this
|
||||
* simply bumps the running total and returns the fresh numbers.
|
||||
*/
|
||||
public function view(string $slug): JsonResponse
|
||||
{
|
||||
$post = Post::where('slug', $slug)->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,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Blog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Comment extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'blog_comments';
|
||||
|
||||
protected $fillable = [
|
||||
'post_id',
|
||||
'name',
|
||||
'email',
|
||||
'body',
|
||||
'is_approved',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_approved' => '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);
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Factories\Blog;
|
||||
|
||||
use App\Models\Blog\Comment;
|
||||
use App\Models\Blog\Post;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
/**
|
||||
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Blog\Comment>
|
||||
*/
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('blog_comments', function (Blueprint $table) {
|
||||
$table->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');
|
||||
}
|
||||
};
|
||||
@@ -1,10 +1,13 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Controllers\Api\Admin\AdminResourceController;
|
||||
use App\Http\Controllers\Api\Admin\CommentAdminController;
|
||||
use App\Http\Controllers\Api\AuthController;
|
||||
use App\Http\Controllers\Api\Blog\CategoryController;
|
||||
use App\Http\Controllers\Api\Blog\CommentController;
|
||||
use App\Http\Controllers\Api\Blog\HomeController;
|
||||
use App\Http\Controllers\Api\Blog\PostController;
|
||||
use App\Http\Controllers\Api\Blog\PostInteractionController;
|
||||
use App\Http\Controllers\Api\Blog\TagController;
|
||||
use App\Http\Controllers\Api\ContactMessageController;
|
||||
use App\Http\Controllers\Api\Website\AboutMeController;
|
||||
@@ -57,6 +60,7 @@ Route::middleware('throttle:60,1')->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']);
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Blog;
|
||||
|
||||
use App\Models\Blog\Comment;
|
||||
use App\Models\Blog\Post;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class CommentTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_only_approved_comments_are_public()
|
||||
{
|
||||
$post = Post::factory()->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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Blog;
|
||||
|
||||
use App\Models\Blog\Comment;
|
||||
use App\Models\Blog\Post;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PostInteractionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_view_increments_the_counter()
|
||||
{
|
||||
$post = Post::factory()->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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user