若同一项目被多次选中,则Laravel将进行验证



在我的应用程序中,我为选定的多个devices提供了add more功能。如果user已选择同一device两次或两次以上,我需要显示错误消息。

这是我的密码。

class ValidateDeviceRequest extends FormRequest
{
private $data = [];
public function __construct()
{
$this->data = request()->all();
}
public function rules()
{
$rules = [
'devices' => ['required', 'array'],
'devices.*.device_company_id' => [
'required', 
'integer', 
'exists:device_companies,id,company_id,' . session()->get('COMPANY_ID')
],
];
foreach($this->data['devices'] as $key => $array)
{
$rules["devices.{$key}.device_id"] = [
'required',
'integer',
"exists:devices,id,device_company_id," . @$array["device_company_id"]
];
}
# returning
return $rules;
}
}

如果您只是检查数组内的重复值。您可以为此使用不同的验证规则。

'devices.*.device_company_id' => [
'distinct',
// ...
]

如果您希望验证模型中的重复项,可以使用规则unique:model

感谢@Tommie。这是我的最终代码。

class ValidateDeviceRequest extends FormRequest
{
private $data = [];
public function __construct()
{
$this->data = request()->all();
}
public function rules()
{
$rules = [
'devices' => ['required', 'array'],
'devices.*.device_company_id' => [
'required', 
'integer', 
'exists:device_companies,id,company_id,' . session()->get('COMPANY_ID')
],
'devices.*.device_company_id' => [
'required',
'distinct',
]
];
foreach($this->data['devices'] as $key => $array)
{
$rules["devices.{$key}.device_id"] = [
'required',
'distinct',
'integer',
"exists:devices,id,device_company_id," . @$array["device_company_id"]
];
}
# returning
return $rules;
}
}

我还发现了Laravel数组对数组中唯一属性的验证,但在表中不需要唯一

相关内容

  • 没有找到相关文章

最新更新