php - 在 Laravel 帖子中限制评论
问题描述
所以这就是问题所在,我有发布和评论的应用程序。但我想限制每个用户的评论,所以如果有 1 个帖子,每个用户只有 1 个评论。可能吗 ?
这是我的store
功能CommentController
:
public function store(Request $request, $post)
{
$this->validate($request, array(
'title' => 'required|max:200',
'desc' => 'required|max:800'
));
$comments = new Comment();
$comments->id_user = Auth::id();
$comments->id_post = $post;
$comments->title = $request->A;
$comments->desc = $request->B;
$comments->save();
return redirect()->route('controller.index');
}
我可以在这个store
函数中添加什么查询来限制用户在 1 个帖子中只能评论一次。谢谢大家希望你能帮助我。
解决方案
您需要检查用户和帖子的评论是否已经存在,这非常简单,如下所示:
if (! Comment::where('id_user', $userId)->where('id_post', $postId)->exists()) {
//save the comment
} else {
// do not save the comment
}
在您的情况下$userId
可能是Auth::user()->id
,并且 $postId 是$post->id
。
推荐阅读
- cordova - Ionic cordova 运行相当于 Capacitor 项目的浏览器
- excel - 太多的 Power Queries 让我内存不足 - 还有其他方法可以做到这一点吗?
- django-models - django 添加另一种类型的角色,例如 request.user.is_newrole
- node.js - 为什么邮递员显示错误消息但反应应用程序没有显示它?
- python-3.x - 有没有办法解决 ContextDecorator 中的 __enter__ AttributeError?
- excel - 计算excel中的工作日数
- android - Jetpack Compose:无法在 TextField 中显示文本
- asp.net - 为什么 IsDBNull 会抛出转换溢出异常?
- dart - 如果不需要加密强的随机数,使用 Random() 优于 Random.secure() 是否有优势?
- azure - 带有多行的 ARM 模板连接