Laravel 的 Input:all() 忽略禁用的输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24142246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel's Input:all() ignores disabled inputs
提问by Razor
While var_dumping the content of Input:all()
with Laravel 4, I noticed that an input generated with the following code is ignored by the framework:
在Input:all()
使用 Laravel 4对内容进行 var_dump 时,我注意到框架忽略了使用以下代码生成的输入:
{{ Form::text('departure', 'Departure', array('class' => 'form-control', 'disabled')) }}
But that the following works as expected:
但是以下内容按预期工作:
{{ Form::text('departure', 'Departure', array('class' => 'form-control')) }}
I have a good reason to disable the user messing with what is in this input field. Yet I need to save it in the database. How should I do this? Disable the disabled
attribute with jQuery when the user submits the form? That's a bit ridiculous, isn't it?
我有充分的理由禁止用户处理此输入字段中的内容。但是我需要将它保存在数据库中。我该怎么做?disabled
当用户提交表单时使用 jQuery禁用该属性?这有点可笑,不是吗?
回答by Razor
Just change disabled
to readonly
只需更改disabled
为readonly
回答by aebersold
It's a bad idea to rely on HTML flags like disabled
or readonly
. The user can easily open up the inspector and change the value of the field. Don't expose this at all in the template, this is business logic which belongs in the model!
依赖像disabled
或 之类的 HTML 标志是一个坏主意readonly
。用户可以轻松打开检查器并更改该字段的值。完全不要在模板中暴露这个,这是属于模型的业务逻辑!
Are you looping over Input::all() to save the fields to the database? If so, you could write something like this:
您是否遍历 Input::all() 以将字段保存到数据库?如果是这样,你可以这样写:
$allowedFields = ["field1", "field2", "field3" ...];
foreach($allowedFields as $field) {
if(Input::has($field) {
$myEloquentModel->{$field} = Input::get($field);
}
}
$myEloquentModel->save();
Benefits: checks only allowed fields, updates only present fields in the actual request.
好处:只检查允许的字段,更新只在实际请求中出现的字段。