解决Laravel表单提交默认将空值转为null

在Laravel中,使用$request->inptu('field'),获取参数值为空的时候,输出的值为null

1
2
3
4
5
6
name: peak
province: 北京市
city: 崇文区
mobile: 18000000000
address: 你猜猜看
zip:

获取 zip 的值

1
2
$zip = $request->input('zip', '');
dd($zip);

发现 zip 并没有输出 '',而是输出 null

原来,在 Illuminate/Foundation/Http 组件中有定义这个中间件

vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

namespace Illuminate\Foundation\Http\Middleware;

class ConvertEmptyStringsToNull extends TransformsRequest
{
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
return is_string($value) && $value === '' ? null : $value;
}
}

解决方法:

在 app/Http/Kernel.php 中注释掉 \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class 即可

1
2
3
4
5
6
7
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
//\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
坚持原创技术分享,您的支持将鼓励我继续创作!
0%