当未在编辑表单中选择图像时,如何默认使用当前图像更新 post。我正在使用 laravel 8

How to by default update a post with the current image when an image has not been chosen in edit form. I am using laravel 8

我希望能够在编辑表单中未选择图像文件时使用当前图像更新 post。

但是,当我尝试在编辑表单中仅保存对 post 标题或 url 的更改时,我收到错误消息,因为我没有同时选择图像文件。

我不断收到的错误是:在 null 上调用成员函数 store()

...该错误指的是我的 PostsController 更新方法中的这一行:

$imagePath = request('image')->store('uploads', 'public');

这是我的 PostsController 中的整个更新方法:

public function update(Post $post, Request $request)
  {
    $data = request()->validate([
      'caption' => 'required',
      'url' => 'required',
      'image' => ['nullable', 'image'],
    ]);

    $imagePath = request('image')->store('uploads', 'public');

    $post->update([
      'caption' => $data['caption'],
      'url' => $data['url'],
      'image' => $imagePath,
    ]);

    return redirect('/users/' . auth()->user()->id);

  }

另外,请注意: 创建方法中需要图像。但是,我在更新方法中将其设置为可空。

如果没有为 post 更新选择图像文件,如何解决此问题以允许使用当前图像?

您可以简单地检查表单中是否有图像文件。如果有,您将上传并使用该路径名进行更新,否则使用旧图像。

if ($request->hasFile('image') {
    $imagePath = request('image')->store('uploads', 'public');
} else {
    $imagePath = $post->image;
}

然后像现在一样输入代码

$post->update([
    'caption' => $data['caption'],
    'url' => $data['url'],
    'image' => $imagePath,
]);
  public function update(Post $post, Request $request)
  {
    $data = request()->validate([
      'caption' => 'required',
      'url' => 'required',
      'image' => ['nullable', 'image'],
    ]);

    $updateData = [
     'caption' => $data['caption'],
     'url' => $data['url'],
   ];

   if (request('image')) {
     $imagePath = request('image')->store('uploads', 'public');
     $updateData['image'] = $imagePath;
   }
   
    $post->update($updateData);

    return redirect('/users/' . auth()->user()->id);

} 

我是这样做的并且它有效@porloscerros Ψ。谢谢你提请我注意。我只需要做一个小调整。