Laravel 5.4 如何将一个字段制空?

我数据库会将一个字段,比如remark 设置为默认值 string。现在我添加数据,remark为"你好",现在我需要将remark设置为空字符串。 api调用方 传了空字符串,但是ConvertEmptyStringsToNull中间件 将empty转为了null , 我应该怎么处理。
目前我的Content-Type 是 application/json,我看国外也在讨论这个问题。https://laracasts.com/discuss...

需要你的帮助,谢谢。

阅读 1.9k
1 个回答

ConvertEmptyStringsToNull 中间件是 Laravel 5.4 才开始加入的。

By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the AppHttpKernel class. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to null. This allows you to not have to worry about these normalization concerns in your routes and controllers.
If you would like to disable this behavior, you may remove the two middleware from your application's middleware stack by removing them from the $middleware property of your AppHttpKernel class.

看官方描述的意思就是为了规范化数据。

如果你确实不想这样处理,可以在 app/Http/Kernel.php 文件中注释掉此 middleware

    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, //注释掉此行
    ];

或者:

从数据库层面,把 remark 字段的默认值设置为 空字符串

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进