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
56 lines
1.5 KiB
PHP
56 lines
1.5 KiB
PHP
<?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,
|
|
]);
|
|
}
|
|
} |