Laravel中如何将文件输入标签的实际存储文件名存入数据库
问题解决:数据库存储文件名与实际存储文件名不一致
你的问题出在**$request->all()的参数数组语法错误**,'TaskFile'和'Commander_id'之间缺少逗号,导致PHP将这两个字符串拼接成了无效键名'TaskFileCommander_id',最终传入数据库的TaskFile值并没有使用你修改后的$newfilename,而是保留了请求里的原始临时文件名。
修复方案
- 修正数组参数的语法错误,给
'TaskFile'后添加逗号; - 更稳妥的方式是直接构造
$attributes数组,避免依赖请求对象的参数过滤,减少出错概率。
修改后的代码
public function store(taskRequestStore $request, TaskService $service) { $destination = base_path('/public/TaskFiles/' . date('Y') . '/' . date('m')); if (!is_dir($destination)) { mkdir($destination, 0777, true); } $destination .= '/'; $filename = rand(1111111, 99999999); $file = $request->file('TaskFile'); $newfilename = $filename . $file->getClientOriginalName(); $file->move($destination, $newfilename); // 直接构造属性数组,确保传入正确的文件名 $attributes = [ 'Caption' => $request->Caption, 'office_id' => $request->office_id, 'Type' => $request->Type, 'TaskFile' => $newfilename, 'Commander_id' => $request->Commander_id, 'OtherOffices' => $request->OtherOffices ]; $office = $service->create($attributes); return redirect()->back()->with(['create' => 'record inserted']); }
补充说明
- 直接构造
$attributes数组可以明确控制每个字段的值,避免因$request->all()参数过滤失误导致的问题; - 修正了代码里的拼写错误
recored为record; - 简化了路径拼接写法,不影响功能实现。
内容的提问来源于stack exchange,提问作者mahdi.gh
相关产品推荐
相关产品推荐

