Aayush Dahal
Aayush Dahal

Reputation: 1182

Laravel image validation on update

My form field looks like:

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

And my validation looks like this:

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

But in case of update, let's say I don't want to change this image field, instead, I just want to change the title filed, but in this case, it is throwing error that, file_upload is required, how could I fix should, should I be uploading image on every update or what? How, could I populate old image value here?

Upvotes: 0

Views: 2854

Answers (2)

John Lobo
John Lobo

Reputation: 15319

You can use 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']

Also you can change if condition to

if (ModelName::whereNotNull('file_upload')->where('id',$this->id)->exists()) {
    
           return false;
    }
    
          return true;
    })

Ref:https://laravel.com/docs/8.x/validation#rule-required-if

Upvotes: 2

archvayu
archvayu

Reputation: 448

on your update method, you can change the validation and check for condition if the file exists on the request

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

Upvotes: 0

Related Questions