Hello,
I am having a problem storing multiple files in a Laravel. I have created a function to store , where my files will store to the directory but it cannot save to the database.
My Request
$rules = [
'file_name.*' => 'mimes:pdf,docx,jpg,png|nullable',
'file_type_id.*' => 'required_with:file_name.*,pdf,docx,jpg,png',
];
my Store Controller
public function store(SupplierRequest $request)
{
$data = $this->handleRequest($request);
DB::beginTransaction();
try {
$supplier = Supplier::create($data);
foreach ($data['file_name'] as $key => $file) {
$value['supplier_id'] = $supplier->id;
$value['file_name'] = $file;
$value['file_type_id'] = $data['file_type_id'][$key];
SupplierFile::create($value);
}
DB::commit();
session()->flash('success', __('message.supplier-store'));
return response()->json(['success' => __('message.supplier-store')]);
} catch (\Throwable$th) {
DB::rollback();
return redirect(app()->getlocale() . '/supplier')->with('error', $th->getMessage());
}
}
My handlefunction()
private function handleRequest($request)
{
$data = $request->all();
$data['file_name'] = [];
if ($request->hasFile('file_name')) {
$supplier_file = $request->file('file_name');
foreach ($supplier_file as $files) {
$filename = $files->getClientOriginalName();
$destination = public_path(config('inventory.supplier_files.directory'));
$successUploaded = $files->move($destination, $filename);
$data['file_name'][] = $filename;
}
}
return $data;
}
Though files will be save to the directory but it will not save to the database why ?