在 Laravel 6 中,请求的参数为空字符串,后端保存为 null 的排查分析

1、前端请求的参数为空字符串。如图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

图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'] ?? '';
永夜