我正在尝试提交一篇简单的博客文章。我使用请求对象作为 DTO 传递数据。
public function store(CreateBlogRequest $createBlogRequest)
{
$user = User::find(1);
$post = $user->posts()->create([$createBlogRequest]);
}
我收到以下错误:
"消息": "找到意外数据。找到意外数据。意外 找到数据。找不到两位数的分钟两位数的秒 找不到尾随数据">
但是,当我将数据作为标准数组传递时,它可以完美运行。
public function store(Request $request)
{
$user = User::find(1);
$post = $user->posts()->create(['title' => $request->title, 'slug' => $request->slug, 'body' => $request->body]);
}
帖子模型
class Post extends Model
{
protected $guarded = [];
protected $dates = ['created_at','updated_at'];
protected $dateFormat = 'Y-m-d H:i:s';
public function user()
{
return $this->belongsTo('AppUser');
}
}
知道这里的问题是什么吗?
你不能只传递请求对象(你也把它包装在一个数组中(。create()
方法需要一个关联数组。
相反,您可以执行在第二个示例中执行的操作。或者像这样:
$post = $user->posts()->create($createBlogRequest->input());
或者更明确(更安全(:
$post = $user->posts()->create($createBlogRequest->only(['title', 'slug', 'body']));
不过,您可能需要使字段$fillable
。