如何从表单中的空字段获取空值?

时间:2017-12-15 19:13:56

标签: php mysql laravel laravel-5

我有一个带有文本字段的表单,该表单存储在数据库的可空列中。我的问题是当用户将该字段留空时。我需要将它存储为空值,但它存储为空字符串。

刀片:

{!! Form::open(array('action' => 'PecaController@store', 'method' => 'POST')) !!}
    {{ csrf_field() }}

    {!! Form::text('nome', old('nome')) !!}
    {!! Form::textarea('descricao', old('descricao'), array('rows' => 3)) !!}

{!! Form::close() !!}

控制器:

public function store(Request $request)
{
    Peca::create([
        'nome' => $request->input('nome'),
        'descricao' => $request->input('descricao')
    ]);

    return redirect(action('PecaController@index'));
}

如何克服这个问题?

2 个答案:

答案 0 :(得分:4)

在Laravel 5.4中,他们引入了可以为您做到的中间件ConvertEmptyStringsToNull

https://laravel.com/api/5.4/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.html

如果您使用的是旧版本并且不想升级,则可能需要启用该功能,或者只是重新创建它。

答案 1 :(得分:1)

在这种情况下,您应该为该属性定义一个mutator。 https://laravel.com/docs/5.5/eloquent-mutators

public function setNomeAttribute($value) {
    $this->attributes['nome'] = $value !== '' ? $value : null;
}

您应该为模型类中的任何属性定义它。