(Laravel)对大规模分配保护的质疑



我正在开发一个包含多个内容的网站,包括一个博客,我对大规模分配保护产生了一些疑问。

当我在博客文章上发表评论时,我认为'可填充'字段将是评论的主体,文章id和parent_comment_id(可选的,仅用于回复评论),但当我来到

ArticleComment::create([
            'author_id' => Auth::user()->id,
            'body' => $request->input('body'),
            'article_id' => $request->input('article_id'),
            'parent_comment_id' => $request->input('parent_comment_id')
        ]);

我发现,即使是author_id字段也应该是可批量分配的,以便将其持久化在数据库中(而不是获得外键失败)。我发现唯一的替代方法是从一个新实例中组装注释并保存:

$comment = new AppArticleComment();
$comment->author_id = Auth::user()->id;
$comment->body = $request->input('body');
$comment->article_id = $request->input('article_id');
$comment->parent_comment_id = $request->input('parent_comment_id');
$comment->save()

但是在这种情况下,不需要有任何'可填充'字段,因为这种方式不会产生任何质量分配异常。

我知道mass-assignment应该是为了防止恶意的数据修改通过post请求,但我没有真正得到,例如,任何人如何修改author_id在第2行,因为它来自Auth而不是来自输入。

我认为在这种情况下,您将使用new ArticleComment($request->input())$comment->fill($request->input())来分配用户可进入的数据,然后分别分配id或非用户可编辑的数据(在您的情况下,author_id)。

$comment = new AppArticleComment($request->input());
$comment->author_id = Auth::user()->id;
$comment->save()

这将防止用户将author_id作为字段发布表单,但仍然允许您快速分配用户字段,而不必在需要的任何地方列出它们。

在您的示例中,没有人能够修改它。但是,如果你想分配这样的东西呢?

ArticleComment::create($request->all());

现在可以修改字段

最新更新