【问题标题】:Submitting post in Laravel - A two minute digit could not be found在 Laravel 中提交帖子 - 找不到两分钟的数字
【发布时间】:2019-07-22 03:04:34
【问题描述】:

我正在尝试提交一篇简单的博客文章。我使用请求对象作为 DTO 传递数据。

public function store(CreateBlogRequest $createBlogRequest)
{
    $user = User::find(1);
    $post = $user->posts()->create([$createBlogRequest]);
}

我收到以下错误:

"message": "发现意外数据。\n发现意外数据。\n意外 找到数据。\n找不到两位数的分钟\n两位数的秒 找不到\n跟踪数据"

但是,当我将数据作为标准数组传递时,它可以完美运行。

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('App\User');
    }
}

知道这里有什么问题吗?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    你不能只传递请求对象(你也将它包装在一个数组中)。 create() 方法需要一个关联数组。

    相反,您可以执行第二个示例中的操作。或者是这样的:

    $post = $user->posts()->create($createBlogRequest->input());
    

    或更明确(更安全):

    $post = $user->posts()->create($createBlogRequest->only(['title', 'slug', 'body']));
    

    您可能需要填写 $fillable 字段。

    【讨论】:

      猜你喜欢
      • 2021-01-25
      • 2015-01-16
      • 2017-09-13
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2017-05-02
      相关资源
      最近更新 更多