更新时的Laravel图像验证



我的表单字段看起来像:

<div class="col-md-6 fv-row form-group" id="file_upload">
<label class="fs-6 fw-bold mb-2" for="file">
File Upload
</label>
<input type="file" name="file_upload" onchange="loadPreview(this);" class="form-control form-control-solid @error('file_upload') is-invalid @enderror"
id="file_upload"  value="" />
<div class="kt_preview_image_container">
<img id="kt_preview_img" src="{{asset('uploads/settings/'.$setting->file_name)}}" class="img-fluid"/>
<a href="!#" class="kt_preview_image_close"><i class="fas fa-times"></i></a>
</div>
@error('file_upload')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>

我的验证是这样的

'file_upload' => 'required|image|mimes:jpeg,png,jpg,svg|max:2048'

但在更新的情况下,假设我不想改变这个图像字段,我只想改变标题字段,但在这种情况下,它会抛出错误,file_upload是必需的,我该如何修复应该,我应该在每次更新时上传图像吗?如何填充旧图像值呢?

您可以使用requiredIf

'file_upload' =>[Rule::requiredIf(function (){
if (!empty(ModelName::find($this->id)->file_upload)) {
return false;
}
return true;
}),'image','mimes:jpeg,png,jpg,svg','max:2048']

也可以将条件改为

if (ModelName::whereNotNull('file_upload')->where('id',$this->id)->exists()) {

return false;
}

return true;
})

裁判:https://laravel.com/docs/8.x/validation rule-required-if

在您的更新方法中,您可以更改验证和检查条件,如果文件存在于请求

'file_upload' => 'nullable|image|mimes:jpeg,png,jpg,svg|max:2048'
if($request->hasFile('file_upload')) {
// if you want to delete previous image
if(file_exists('path/'.$setting->file_name) {
unlink('path/'.$setting->file_name);
}
$file = $request->file('file_upload');
$extension = $file->extension();
$fileName = 'your-file-name';
$upload = $file->storeAs('path', $fileName);
$setting->file_name = $fileName;
}

相关内容

  • 没有找到相关文章

最新更新