简体   繁体   English

Laravel 验证 - 不同属性规范

[英]Laravel validation - Different Attributes Specifications

I'm using a LaravelMiddleware, which should check for Access.我正在使用 LaravelMiddleware,它应该检查 Access。 Therefore, I check for a specific Attributes, which sometimes have different names.因此,我检查一个特定的属性,这些属性有时具有不同的名称。

EG:例如:

  1. $request->key $请求->密钥
  2. $request->moduleKey $request->moduleKey

Im asking if there is a possiblitiy to check for 2 different attributes specifications?我问是否有可能检查 2 个不同的属性规范?

Like so:像这样:

$data = $request->validate([
   'key|moduleKey' => ['required', 'numeric'],   
]);

It's not possible this way, but you have 2 other options:这种方式是不可能的,但您还有另外两个选择:

Validation验证

https://laravel.com/docs/9.x/validation#rule-required-without https://laravel.com/docs/9.x/validation#rule-required-without

$data = $request->validate([
   'key' => ['required_without:moduleKey', 'numeric'],   
   'moduleKey' => ['required_without:key', 'numeric'],   
]);

but the problem is you still dont know which one you need unless you always get them both: $data['key']?? $data['moduleKey']但问题是你仍然不知道你需要哪一个,除非你总是同时得到它们: $data['key']?? $data['moduleKey'] $data['key']?? $data['moduleKey']

You can also update the request beforenhand:您还可以事先更新请求:

$request['key'] = $request['key'] ?? $request['moduleKey'];
$data = $request->validate([rules]);

this code above you could put in a middleware to make sure every request always have the "key" variable in the request.您可以将上面的这段代码放入一个中间件中,以确保每个请求在请求中始终具有“key”变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM