试图添加一个评论在我的博客 , 所以我得到这个新的错误。
Add [body] to fillable property to allow mass assignment on [App\comment].
这是我的控制器。
public function store (blog $getid)
{
comment::create([
'body' =>request('body'),
'blog_id'=> $getid->id
]);
return view('blog');
}
而这是形式。
<form method="POST" action="/blog/{{$showme->id}}/store" >
@csrf
<label> Commentaire </label> </br>
<textarea name="body" id="" cols="30" rows="2"></textarea> </br>
<button type="submit"> Ajouter commentaire</button>
</form>
web.php。
Route::post('blog/{getid}/store', 'commentcontroller@store');
为了避免填写任何给定的属性。Laravel
具有质量对齐保护。您要填充的属性应该在 $fillable
属性的模型。
class Comment {
$fillable = ['body', 'blog_id'];
}
奖励
为了跟上标准。你不应该用小写字母来命名你的班级,应该是 Blog
和 Comment
,都在 PHP
代码和文件名中。
Id不应该被填充,而是被关联,所以它们将被正确加载到模型上。所以想象一下你的 Comment
具有博客关系的模型。
class Comment {
public function blog() {
return $this->belongsTo(Blog::class);
}
}
你应该把它赋值。在这里,你将通过使用Model绑定来获取Blog,因此你应该将参数$blog命名为,这样绑定才会有效。另外使用Request依赖注入,也是一个不错的方法。
use Illuminate\Http\Request;
public function store(Request $request, Blog $blog) {
$comment = new Comment(['body' => $request->input('body')]);
$comment->blog()->associate($blog);
$comment->save();
}