Laravel: 自定义数组验证取决于之前选择的值
Laravel: custom array validation depends on previous selected value
Laravel版本:7.x
我已经使用硬编码有效 device_company_id
(与所选设备相关联)测试了代码,它工作正常。
表
device_companies
|- id
|- company_id
|- title
|- ...
devices
|- id
|- device_company_id
|- ...
请求数据
Array
(
...
[devices] => Array
(
[0] => Array
(
[device_company_id] => 1
[device_id] => 2
[device_inventory_id] => null
[amount] =>
[refundable] =>
[description] =>
)
)
)
规则:
...
$rules = array_merge($rules, [
'devices' => [
'required',
'array'
],
'devices.*.device_company_id' => [
'required',
'integer',
'exists:device_companies,id,company_id,' . auth()->user()->id
],
'devices.*.device_id' => [
'required',
'integer',
'exists:devices,id,device_company_id,devices.*.device_company_id'
],
]);
...
我需要 exists
验证器的自定义验证规则来验证 device
是否确实属于所选的 device_company
。因为我不希望任何人打开检查工具,更改值并导致应用程序出错或类似的事情。
这是 link 我找到参考的地方 https://ericlbarnes.com/2015/04/04/laravel-array-validation/
我的代码:
...
$rules = [
...other rules
];
$newRules = [
'devices' => [
'required',
'array'
],
'devices.*.device_company_id' => [
'required',
'integer',
'exists:device_companies,id,company_id,' . auth()->user()->id
],
];
foreach($data['devices'] as $key => $array)
{
$newRules["devices.{$key}.device_id"] = [
'required',
'integer',
"exists:devices,id,device_company_id,{$array["device_company_id"]}",
];
}
$rules = array_merge($rules, $newRules);
...
尽管这段代码对我有用,但我觉得这不是正确的方法。感觉有点绕过而不是正确的解决方案。如果有人找到更好的解决方案,请 post 你的答案。
希望这对某人有所帮助。谢谢:)
Laravel版本:7.x
我已经使用硬编码有效 device_company_id
(与所选设备相关联)测试了代码,它工作正常。
表
device_companies
|- id
|- company_id
|- title
|- ...
devices
|- id
|- device_company_id
|- ...
请求数据
Array
(
...
[devices] => Array
(
[0] => Array
(
[device_company_id] => 1
[device_id] => 2
[device_inventory_id] => null
[amount] =>
[refundable] =>
[description] =>
)
)
)
规则:
...
$rules = array_merge($rules, [
'devices' => [
'required',
'array'
],
'devices.*.device_company_id' => [
'required',
'integer',
'exists:device_companies,id,company_id,' . auth()->user()->id
],
'devices.*.device_id' => [
'required',
'integer',
'exists:devices,id,device_company_id,devices.*.device_company_id'
],
]);
...
我需要 exists
验证器的自定义验证规则来验证 device
是否确实属于所选的 device_company
。因为我不希望任何人打开检查工具,更改值并导致应用程序出错或类似的事情。
这是 link 我找到参考的地方 https://ericlbarnes.com/2015/04/04/laravel-array-validation/
我的代码:
...
$rules = [
...other rules
];
$newRules = [
'devices' => [
'required',
'array'
],
'devices.*.device_company_id' => [
'required',
'integer',
'exists:device_companies,id,company_id,' . auth()->user()->id
],
];
foreach($data['devices'] as $key => $array)
{
$newRules["devices.{$key}.device_id"] = [
'required',
'integer',
"exists:devices,id,device_company_id,{$array["device_company_id"]}",
];
}
$rules = array_merge($rules, $newRules);
...
尽管这段代码对我有用,但我觉得这不是正确的方法。感觉有点绕过而不是正确的解决方案。如果有人找到更好的解决方案,请 post 你的答案。
希望这对某人有所帮助。谢谢:)