【问题标题】:Method Illuminate\Database\Eloquent\Collection::update does not exist方法 Illuminate\Database\Eloquent\Collection::update 不存在
【发布时间】:2019-02-09 20:14:15
【问题描述】:

有人帮我解决这个错误吗?当我尝试更新帖子时会发生这种情况, 这是我的更新功能

public function update(Requests\PostRequest $request, $id)
    {
        $post = Post::findOrFail($id);
        $data = $this->handleRequest($request);
        $post->update($data);
        return redirect('/blog/post')->with('message','Your posts was updated successfully');
    }

这是我的 handleRequest 函数

private function handleRequest($request)
    {
        $data = $request->all();

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $fileName = $image->getClientOriginalName();
            $destination = $this->uploadPath;

            $image->move($destination, $fileName);

            $data['image'] = $fileName;
        }

        return $data;
    }

【问题讨论】:

  • 你确定是这段代码抛出了错误吗?也许重定向页面中的逻辑会引发错误?这段代码在我看来没问题...
  • 当我移除 $post->update($data); 时重定向成功;
  • 为什么你有这个“Requests\PostRequest”而不是Request?
  • 验证输入
  • 你的问题在于这一行 $post->update($data)

标签: php laravel


【解决方案1】:

您正在访问一个collection 实例,您需要访问底层模型:

foreach($post as $p){//loop through an Eloquent collection instance
    $p->fill($data);//mass assign the new values
    $p->save();//save the instance
}

【讨论】:

  • 抛出错误的地方,它所在的确切行,删除更新函数调用并用正确的变量名替换它
  • 它有另一个错误,它说 SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'testp' for key 'posts_slug_unique' (23000)
  • 您的数据库表中有唯一字段,并且您正在尝试使用已经存在的另一个字段值更新该字段值。我猜
猜你喜欢
  • 2021-08-02
  • 2021-06-08
  • 2020-11-21
  • 2021-09-08
  • 2020-11-13
  • 2019-12-11
  • 2020-02-04
  • 2019-11-12
  • 2019-05-24
相关资源
最近更新 更多