I have this function that will update the data as showing below:
public function update(Request $request, OutstandingPayment $outstandingPayment)
{
$request->validate([
'file' => 'required|mimes:jpg,jpeg,png,csv,txt,xlx,xls,pdf|max:2048',
'payment_voucher_file_ref_no' => 'required|string',
'payment_voucher_date' => 'required|string',
]);
if ($request->hasFile('file')) {
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('file')->move(public_path('uploads/outstandingPayment'), $file_name);
$request->payment_voucher_supporting_doc = time().'_'.$request->file->getClientOriginalName();
$request->path = '/storage/' . $file_path;
}
$postData = [
'payment_voucher_file_ref_no' => $request->payment_voucher_file_ref_no,
'payment_voucher_date' => $request->payment_voucher_date,
'payment_voucher_supporting_doc' => $request->payment_voucher_supporting_doc,
'path' => $request->path,
];
$outstandingPayment->update($postData);
}
The above function is working fine but only if i uploaded new file
Note: "File" is -> "file" is "payment_voucher_supporting_doc" i am passing it in the request as "file" and place it in "payment_voucher_supporting_doc"
But in my case now, if there are no changes on "file" i want the current one to stay the same
I tried to add "else" if there is no file and assign "payment_voucher_supporting_doc" to outstandingPayment->payment_voucher_supporting_doc" but the response show that still "file" is required
How can i achieve that?
3
Answers
I don’t find best ways on your code about
whether your upload file
had changed or not.
For example, can you try to set
guard method
before update your file?like this:
how do you check file is newest or not ? name or contents detail?
ps: you use
time()
method some places. if your functionprocessing speed is slow, your file name will be different like 160000_hoge.png and 160003_hoge.png.
so, I recommend to fix that. 🙂
Just make your validation
nullable
and then put every field that you want update with file in if block:a hypothetical example(because your code is so long and I use mobile to type this answer): I want update user’s profile and name but i want profile will be update if there is a picture in my request:
In my example, profile field will be updated if I upload a picture, otherwise just user’s name will be updated
Yikes. but your file is required because you have it as required in your validation. Also this can be cleaned up quite a bit like using a form request object for the validation https://laravel.com/docs/9.x/validation#form-request-validation