首页 > 解决方案 > 如何使用 laravel 6 在表单编辑中获取图像以进行更新

问题描述

我添加了产品的类型和图像,它添加成功,图像在索引中显示得很好,但我的问题是编辑,当我想编辑产品时,我点击按钮编辑它检索产品类型但它没有恢复相同图片 我编写了代码value = "{{$ file-> image}}"但无法正常工作。

文件控制器.php

public function store(Request $request)
    {
        $request->validate([
         'type'       => ['bail','required'],
         'image'      => ['bail','mimes:jpeg,jpg,png,gif,svg','required','max:2048'],
         ]);
        $file = new File(); 
        $file->type = $request->type;
        if($request->hasFile('image'))
       {
        $path = $request->image->store('annonces');
        $file->image = $path;
        }
        $file->save();
        return Redirect::to("file")
        ->withSuccess('Great! file has been successfully uploaded.');
    }

编辑刀片.php

<form method="post" action="{{ url('file/'.$file->id) }}" enctype="multipart/form-data">
  {{ csrf_field() }}
          <div class="form-group">
           <label>type <span class="text-hightlight">*</span></label>
                <select class="form-control" value="{{ $file->type }}" name="type">
                    <option></option> 
                    <option value="1" {{ $file->type == "type1" ? 'selected' : '' }}>type1</option>  
                    <option value="2" {{ $file->type == "type2" ? 'selected' : '' }}>type2</option> 
                    <option value="3" {{ $file->type == "type3" ? 'selected' : '' }}>type3</option> 
                </select>
          </div> 
          
          <div class="form-group">
              <label>image product<span class="text-hightlight">*</span></label>
              <input type="file" name="image" value="{{ $file->image }}" class="form-control @error('image') is-invalid @enderror">
          </div>
          <button type="submit" class="btn btn-success" style="margin-top:10px">update</button>
</form> 

标签: phplaravel

解决方案


首先,您确保执行此命令,这会创建一个指向公共存储的符号链接

php artisan storage:link

您会注意到在 storage/app 中创建了一个公用文件夹。其次,您需要将图像保存到公共磁盘中:例如:

$path = Storage::disk('public')->putFile('annonces', $request->file('image'));

然后在你的刀片上,你可以简单地这样做来显示图像:

{{ \Storage::disk('public')->url($file->image) }}

我认为它不会显示在输入上,但也许您可以在输入上方的标签中显示图像的预览,因此它显示该用户的当前头像


推荐阅读