php 验证或删除 laravel 中的额外字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35327679/
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
Validate or remove for extra fields in laravel
提问by Son
It's posible to validate request with rules for additional fields, or remove that fields from request?
是否可以使用附加字段的规则验证请求,或者从请求中删除该字段?
Simple example, I have FormRequest object with rules:
简单的例子,我有带有规则的 FormRequest 对象:
public function rules() {
return [
'id' => 'required|integer',
'company_name' => 'required|max:255',
];
}
And when I get post request with any other fields I want to get error/exception in controller or I want to get only id and company_name fields, with no any others. It's exist any feature in laravel with that, or I must make it in my way?
当我收到任何其他字段的发布请求时,我想在控制器中收到错误/异常,或者我只想获取 id 和 company_name 字段,而没有任何其他字段。它在 Laravel 中是否存在任何功能,或者我必须以我的方式实现它?
回答by Can Celik
Your post request with laravel has more stuff than just your form input so you need to check Request to see what is inside.
你对 laravel 的 post 请求不仅仅是你的表单输入,所以你需要检查 Request 以查看里面有什么。
To get only the fields you want you can use:
要仅获取您想要的字段,您可以使用:
$request->only(['fieldname1', 'fieldname2', 'fieldname3']);
or
或者
$request->except(['fieldnameYouDontWant1', 'fieldnameYouDontWant2', 'fieldnameYouDontWant3']);
to exclude the ones you don't want.
排除那些你不想要的。
回答by Anton Ganichev
To remove key from request in Laravel, use:
要从 Laravel 中的请求中删除密钥,请使用:
$request->request->remove('key')
回答by user3743266
Since Laravel 5.5 you can do this in your controller:
从 Laravel 5.5 开始,您可以在控制器中执行此操作:
public function store(StoreCompanyRequest $request)
{
Company::create($request->validated());
}
The validated() function returns only the fields that you have validated and removes everything else.
Verified() 函数仅返回您已验证的字段并删除其他所有字段。
回答by Haidang Nguyen
I have a new solution for this, create a new function in your form request class:
我有一个新的解决方案,在你的表单请求类中创建一个新函数:
public function onlyInRules()
{
return $this->only(array_keys($this->rules()));
}
Then in your controller, call $request->onlyInRules()
instead of $request->all()
然后在您的控制器中,调用$request->onlyInRules()
而不是$request->all()
回答by kmuenkel
Things get a little trickier when you start getting into nested array element validations, especially if wildcards are involved. Put this in your custom Request
class, and inject it into your controller method. Should cover all cases.
当您开始进行嵌套数组元素验证时,事情会变得有点棘手,尤其是在涉及通配符时。把它放在你的自定义Request
类中,并将它注入到你的控制器方法中。应该涵盖所有情况。
public function authorize()
{
//Dot notation makes it possible to parse nested values without recursion
$original = array_dot($this->all());
$filtered = [];
$rules = collect($this->rules());
$keys = $rules->keys();
$rules->each(function ($rules, $key) use ($original, $keys, &$filtered) {
//Allow for array or pipe-delimited rule-sets
if (is_string($rules)) {
$rules = explode('|', $rules);
}
//In case a rule requires an element to be an array, look for nested rules
$nestedRules = $keys->filter(function ($otherKey) use ($key) {
return (strpos($otherKey, "$key.") === 0);
});
//If the input must be an array, default missing nested rules to a wildcard
if (in_array('array', $rules) && $nestedRules->isEmpty()) {
$key .= ".*";
}
foreach ($original as $dotIndex => $element) {
//fnmatch respects wildcard asterisks
if (fnmatch($key, $dotIndex)) {
//array_set respects dot-notation, building out a normal array
array_set($filtered, $dotIndex, $element);
}
}
});
//Replace all input values with the filtered set
$this->replace($filtered);
//If field changes were attempted, but non were permitted, send back a 403
return (empty($original) || !empty($this->all()));
}
回答by Mehul Panchasara
You can use except method of request which will give you fields except for the given fields
您可以使用 except 请求方法,该方法将为您提供除给定字段之外的字段
$request = $request->except('your_field');
if you want to remove multiple fields from request you can pass array of the fields
如果你想从请求中删除多个字段,你可以传递字段数组
$request = $request->except(['field_1','field_2',...])
回答by Andrii Yasynovyi
Starting form Laravel 5.5 you can call validate
method right on Request
e.g.
从 Laravel 5.5 开始,您可以直接调用validate
方法,Request
例如
class YourController extends Controller
{
public function store(Request $request) {
$cleanData = $request->validate([
'id' => 'required|integer',
'company_name' => 'required|max:255',
]);
// Now you may safely pass $cleanData right to your model
// because it ONLY contains fields that in your rules e.g
$yourModel->create($cleanData);
}
}
回答by Son
I did it by override method validate() in FormRequest class.
我是通过 FormRequest 类中的覆盖方法 validate() 做到的。
abstract class MyFormRequest extends FormRequest {
public function validate() {
foreach ($this->request->all() as $key => $value) {
if (!array_key_exists($key, $this->rules())) {
throw new ValidationException("Field " . $key . " is not allowed.");
}
}
parent::validate();
}
}
I think it's not best way, but it's works. I should upgrade it to show info about all wrong fields at once :)
我认为这不是最好的方法,但它是有效的。我应该升级它以立即显示所有错误字段的信息:)
回答by smartrahat
You can do it through your controller. You can send only two or certain fields to database. Use $request->only()
instead of $request->all()
and pass a array of data you want to save in database. Your controller
's store()
method should look like this:
你可以通过你的控制器来做到这一点。您只能将两个或某些字段发送到数据库。使用$request->only()
代替$request->all()
并传递要保存在数据库中的数据数组。你controller
的store()
方法应该是这样的:
public function store(Request $request)
{
ModelName::create($request->only(['id','company_name']));
return redirect('RouteName');
}
回答by Daniel Angel
$request->validated();
will return only the validated data.
将只返回经过验证的数据。
In your controller method:
在您的控制器方法中:
public function myController(ValidationRequest $request) {
$data = $request->validated();
}