欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

解决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,
   ];



来自 http://xinyufeng.net/2020/05/28/%E8%A7%A3%E5%86%B3Laravel%E8%A1%A8%E5%8D%95%E6%8F%90%E4%BA%A4%E9%BB%98%E8%AE%A4%E5%B0%86%E7%A9%BA%E5%80%BC%E8%BD%AC%E4%B8%BAnull/


普通分类: