You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:57:02