如何在 Laravel 5.5 中自动将数据从请求映射到模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47745912/
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
How to auto map data from Request to Model in Laravel 5.5
提问by Thanh Dao
I would like to submit my form with many of fields.
As the documentation
我想提交包含许多字段的表单。
作为文档
$flight = new Flight;
$flight->name = $request->name;
$flight->param1 = $request->param1;
$flight->param2 = $request->param2;
...
$flight->param_n = $request->param_n;
$flight->save();
Its a bad idea if have too much fields.
I'm looking for any script like:
如果字段太多,这是一个坏主意。
我正在寻找任何脚本,例如:
$flight = new Flight;
$flight->save($request->all());
But $request->all()
function got unnecessary fields
What is the best way to do?
但是$request->all()
函数得到了不必要的字段
最好的方法是什么?
回答by Mathew Tinsley
You could use the model $fillable
array for this so long as your model properties match your request properties exactly.
$fillable
只要您的模型属性与您的请求属性完全匹配,您就可以为此使用模型数组。
$flight = new Flight();
$data = $request->only($flight->getFillable());
$flight->fill($data)->save();
You'll need to specify the fillable fields for any model that you would like to use this behavior for.
您需要为要使用此行为的任何模型指定可填写字段。
For Laravel 5.4 and lower use intersect
instead of only
对于 Laravel 5.4 及更低版本,使用intersect
代替only
Otherwise you can just whitelist the properties you want from the request
否则,您可以将请求中所需的属性列入白名单
$data = $request->only(['param1', 'param2' ...]);
回答by Muhammad Sadiq
There are various ways. you can exclude unwanted values as
$data = $request->except(['_token','_method','etc']);
The best way would be validated data. viz apply validation on your form inputs on server side.
$validated_data = $request->validate(['field1'=>'required','field2'=> 'required']);
有多种方式。您可以排除不需要的值
$data = $request->except(['_token','_method','etc']);
最好的方法是验证数据。即对服务器端的表单输入应用验证。
$validated_data = $request->validate(['field1'=>'required','field2'=>'required']);
etc. you can apply desired validations on each field and only validated fields will be in $validated_data variable, and then you can save them.
等等,您可以在每个字段上应用所需的验证,只有经过验证的字段才会在 $validated_data 变量中,然后您可以保存它们。