thinkphp 6 做资讯发布和草稿预览时,公开入口只查询已发布记录。草稿预览放在已有授权的后台,发布操作用 post,把状态从 draft 条件更新为 published。
公开详情只读取已发布记录
示例假定 articles 表含 id、title、body、status 和 published_at。下面的方法放进公开控制器。
public function read(int $id)
{
$article = \think\facade\Db::name('articles')
->field('id,title,body,published_at')
->where('id', $id)
->where('status', 'published')
->find();
return $article ? json($article) : json(['message' => 'Not found'], 404);
}
草稿和不存在的 ID 都应得到 404。公开列表也要加相同的发布条件。
在受保护的后台读取草稿
下面两个方法只能放进已有管理员鉴权的后台控制器。预览路由在后台分组内注册,并沿用项目现有文章访问权限。
立即学习“PHP免费学习笔记(深入)”;
public function preview(int $id)
{
$draft = \think\facade\Db::name('articles')
->field('id,title,body')
->where('id', $id)
->where('status', 'draft')
->find();
if (!$draft) {
return json(['message' => 'Draft not found'], 404);
}
return response(json_encode($draft, JSON_UNESCAPED_UNICODE), 200, [
'Content-Type' => 'application/json; charset=utf-8',
'Cache-Control' => 'private, no-store',
]);
}
草稿响应避免被公共缓存保存。使用模板展示时需要转义标题和正文。
发布时限制原状态并验证重复请求
将 publish 方法挂到已保护的 POST 路由。若使用基于 Cookie 的管理后台,提交时沿用现有 CSRF 检查。
public function publish(int $id)
{
$changed = \think\facade\Db::name('articles')
->where('id', $id)
->where('status', 'draft')
->update([
'status' => 'published',
'published_at' => date('Y-m-d H:i:s'),
]);
return $changed === 1
? json(['status' => 'published'])
: json(['message' => 'No draft to publish'], 409);
}在测试库先验公开详情返回 404、后台预览返回 200。发布后公开详情应可读取,第二次提交应得到 409。



















