laravel 中 [App\comment] 的批量分配
mass assignment on [App\comment] in laravel
试图在我的博客中添加评论,所以我收到了这个新错误:
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);
}
}
您应该改为分配它。在使用模型绑定获取博客的地方,您应该将参数命名为 $blog,这样绑定才会起作用。另外使用请求依赖注入,也是一个很好的方法。
use Illuminate\Http\Request;
public function store(Request $request, Blog $blog) {
$comment = new Comment(['body' => $request->input('body')]);
$comment->blog()->associate($blog);
$comment->save();
}
试图在我的博客中添加评论,所以我收到了这个新错误:
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);
}
}
您应该改为分配它。在使用模型绑定获取博客的地方,您应该将参数命名为 $blog,这样绑定才会起作用。另外使用请求依赖注入,也是一个很好的方法。
use Illuminate\Http\Request;
public function store(Request $request, Blog $blog) {
$comment = new Comment(['body' => $request->input('body')]);
$comment->blog()->associate($blog);
$comment->save();
}