php 将 [title] 添加到可填充属性以允许在 [App\Post] 上进行批量分配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53793841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add [title] to fillable property to allow mass assignment on [App\Post]
提问by Muhammad Mansha
While inserting data in Mysql I have encountered with the following error:
在 Mysql 中插入数据时,我遇到了以下错误:
"Add [title] to fillable property to allow mass assignment on [App\Post]."
“将 [title] 添加到可填充属性以允许在 [App\Post] 上进行批量分配。”
Here is my code:
这是我的代码:
$post = Post::create([
'title' => $request->input('title'),
'body' => $request->input('body')
]);
While when I use another way to insert data, it is working fine: Following code is working fine :
当我使用另一种方式插入数据时,它工作正常:以下代码工作正常:
//Create Post
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
Could anyone explain why upper portion of code is throwing an error?
谁能解释为什么上面的代码会抛出错误?
回答by Walter Cejas
Add title to the fillable array in your model Post, to allow saving through create and massive methods
为模型 Post 中的可填充数组添加标题,以允许通过创建和大规模方法进行保存
protected $fillable = ['title'];
回答by Armin
The alternative to protected $fillable = ['title'];
would be :
的替代方法protected $fillable = ['title'];
是:
protected $guarded = [];
and leave it as an empty array, without the need to define anything inside.
It is the exact opposite of $fillable
, sort of like telling the database to accept everything, except the fields you specify inside the $guarded
array.
并将其保留为空数组,无需在内部定义任何内容。它与 完全相反$fillable
,有点像告诉数据库接受所有内容,除了您在$guarded
数组中指定的字段。
回答by Alimon Karim
For $fillable all
对于 $fillable 所有
protected $guarded = ['id'];
回答by Saman Ahmadi
For mass assignment you should define "Fillable array" in your model (App\Post)
对于质量分配,您应该在模型中定义“Fillable array”(App\Post)
So your model should be something like this:
所以你的模型应该是这样的:
class Post extends Model
{
protected $fillable = ['title','body']; //<---- Add this line
// ...
}
More information: [https://laravel.com/docs/5.7/eloquent#mass-assignment][1]
更多信息:[ https://laravel.com/docs/5.7/eloquent#mass-assignment][1]
回答by Punit khandelwal
This error appeared because you didn't declare a variable in your Model - you should define it in your class like so;
出现此错误是因为您没有在模型中声明变量 - 您应该像这样在类中定义它;
protected $fillable = ['title'];
回答by Vinesh Goyal
In your Post model, there will be a $fillable
array variable which you have to add 'title'.
在您的 Post 模型中,将有一个$fillable
数组变量,您必须添加“title”。
For More info: What does "Mass Assignment" mean in Laravel?