Laravel saveImage函数如何仅在指定行将$requestField下划线替换为横杠
解决方案
完全可以仅在该函数内修改对应行实现需求,不需要调整外部调用逻辑,也不会影响函数内其他位置$requestField的原始值使用。
修改方法
只需要将路径拼接的两行代码中,$requestField替换为str_replace('_', '-', $requestField)即可,该方法只会临时将下划线替换为横杠,不会改变原变量本身的存储值。
修改后完整代码:
public function saveImage(Request $request, $requestField, $path) { if ($request->hasFile($requestField)) { $image_path = public_path($this->{ $requestField }); if (File::exists($image_path)) { File::delete($image_path); } $file = $request->file($requestField); $uploadname = $this->getUploadName($file); $pathFull = public_path($path); if (!File::exists($pathFull, 0775, true)) { File::makeDirectory($pathFull, 0775, true); } Image::make($file)->save($pathFull. str_replace('_', '-', $requestField). '-'. $uploadname); $this->{ $requestField } = $path. str_replace('_', '-', $requestField). '-'. $uploadname; return $file; } return false; }
逻辑说明
- 函数其他位置用到
$requestField的逻辑(包括请求参数判断、旧文件路径读取、类属性赋值的键名等)仍然使用原始带下划线的参数值,完全符合需求 str_replace为临时字符串转换操作,不会修改$requestField变量本身的存储值,不会对其他逻辑产生额外影响
内容的提问来源于stack exchange,提问作者chu
相关产品推荐
相关产品推荐

