Illuminate\Database\Eloquent\Collection::update方法不存在。

3

能否有人帮我解决这个错误?这个错误发生在我尝试更新文章时,以下是我的更新函数:

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;
    }

你确定是这段代码引发了错误吗?也许重定向页面中的逻辑引发了错误?在我看来,这段代码没问题... - David Heremans
当我删除 $post->update($data); 后,它成功重定向。 - Chairuman
为什么你使用"Requests\PostRequest"而不是"Request"? - Emeka Okafor
验证输入 - Chairuman
你的问题出在这一行 $post->update($data)。 - CodeBoyCode
1个回答

4
你正在访问一个“collection”实例,你需要访问底层模型:
foreach($post as $p){//loop through an Eloquent collection instance
    $p->fill($data);//mass assign the new values
    $p->save();//save the instance
}

在抛出错误的地方,准确的行数,在移除更新函数调用后,使用正确的变量名称替换它。 - user3647971
它有另一个错误,它说SQLSTATE[23000]:完整性约束冲突:1062重复条目“testp”以键“posts_slug_unique”(23000) - Chairuman
您的数据库表中有一个唯一字段,您正在尝试使用已经存在的另一个字段值来更新该字段值。我猜... - user3647971

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接