1、前端请求的参数为空字符串。如图1

{
"image": null,
"align": "center",
"title": "Image with text overlay",
"description": "Use overlay text to give your customers insight into your brand. Select imagery and text that relates to your style and story.",
"button": {
"text": "Shop Now",
"url_object": {
"ID": 1,
"children": [],
"key": 3944,
"object": "home",
"object_id": 1,
"title": "Home",
"url": "/"
},
"url": "/"
},
"text_color": "#fff",
"button_text_color": "#000",
"button_background_color": "#fff",
"show_overlay": false,
"opacity": 0
}
2、后端保存后,title 的值为 null 。
{
"image": null,
"align": "center",
"title": null,
"description": "Use overlay text to give your customers insight into your brand. Select imagery and text that relates to your style and story.",
"button": {
"text": "Shop Now",
"url_object": {
"ID": 1,
"children": [],
"key": 3944,
"object": "home",
"object_id": 1,
"title": "Home",
"url": "/"
},
"url": "/"
},
"text_color": "#fff",
"button_text_color": "#000",
"button_background_color": "#fff",
"show_overlay": false,
"opacity": 0
}
3、在后端打印所有请求参数,var_dump($request->all());。确认 title 的值已经被转换为 null。如图2

4、参考:https://learnku.com/docs/laravel/6.x/validation/5144#6633ca 。默认情况下,在 Laravel 应用的全局中间件堆栈 App\Http\Kernel 类中包含了 ConvertEmptyStringsToNull 中间件。此中间件会将空字符串转换为 Null。
5、但是,如果贸然删除掉此中间件,担心其他功能会受到影响,影响范围很难评估。查看 ConvertEmptyStringsToNull 的实现
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
return is_string($value) && $value === '' ? null : $value;
}
6、决定反向转换,在响应给前端时,判断是否为 null ,如果是,则转换为空字符串。最终决定使用 NULL 合并运算符。
// is_null($item['title']) ? '' : $item['title'];
$item['title'] ?? '';
PHP / Laravel / Yii2 老项目维护与长期技术支持
如果你的 PHP / Laravel / Yii2 项目已经上线,但遇到原开发离职、Bug 长期无人修复、接口不稳定、性能下降、代码难以接手等问题,可以联系我做一次远程技术排查。
适合以下情况:
✅ 老旧 PHP 系统无人维护
✅ Laravel / Yii2 项目 Bug 修复
✅ 后台管理系统小功能迭代
✅ RESTful API 接口排查
✅ MySQL / Redis / Nginx 性能问题
✅ 长期远程兼职维护
可先从一次小问题开始:
✅ 线上报错排查
✅ 接口异常分析
✅ 慢查询与性能瓶颈定位
✅ 代码结构初步评估
✅ 部署环境与日志检查
如需咨询,请联系我,并注明:PHP 维护咨询。
联系方式:
Telegram:@shuijingwan
微信:13980074657
邮箱:shuijingwanwq@gmail.com
