Reputation: 57
I'm developing a website with several contents, including a blog, and I've come up to some doubts concerning mass assignment protection.
When I'm posting a comment on a blog article, I suppose the 'fillable' fields would be the comment's body, the article id and the parent_comment_id (optional and used only for replies to a comment), but when I came up to
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')
]);
I found out that even the author_id field should be mass-assignable in order to have it persisted in the database (and not to get a foreign key failure). The only alternative I found would be assembling the comment from a new instance and saving it:
$comment = new App\ArticleComment();
$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()
but in this case there would be no need to have any 'fillable' field, because this way does not generate any mass-assignment exception.
I know that mass-assignment is supposed to prevent malicious data alteration through a post request, but I don't really get, for example, how would anybody modify the author_id in row 2 since it comes from Auth and not from input.
Upvotes: 2
Views: 84
Reputation: 1528
I think in this case, you would use new ArticleComment($request->input())
or $comment->fill($request->input())
to assign the user-enterable data, then assign the id's or non-user editable data (in your case, the author_id
) separately.
$comment = new App\ArticleComment($request->input());
$comment->author_id = Auth::user()->id;
$comment->save()
This would prevent users from POSTing a form with author_id as a field, but still allows you to quickly assign the user fields, without having to list them everywhere you need to do it.
Upvotes: 1
Reputation: 4097
In your example, no one will be able to modify it. However, what if you wanted to assign something like this?
ArticleComment::create($request->all());
Now the fields can be modified. That is what Mass Assignement is meant to protect against.
Upvotes: 0