php - Laravel 验证规则 - 必须至少更改一个输入值
问题描述
我有一个带有标题、副标题、日期的模型,并且正在构建一个允许用户提交更改请求的表单。
如何验证以确保至少进行了一次编辑,将输入字段与数据库值进行比较?
我认为下面将确保输入的标题与“不同:”中的值不同,但我如何只为至少一个字段执行此操作?
public function rules()
{
return [
'title' => [
'required',
'different:Dynamic Title name here',
'string',
'max:60',
'not_regex:/[\x{1F600}-\x{1F64F}]/u'
],
'subtitle' => [
'string',
'nullable',
'max:90',
'not_regex:/[\x{1F600}-\x{1F64F}]/u'
]
];
}
例如,显示标题、副标题、日期字段。用户必须从当前设置的数据库值中至少编辑其中一个才能提交。
解决方案
我不知道您的解决方案,但我建议您看一下 isDirty() 函数。
/**
* this will return false, because after we get the record from
* database, there's no attribute of it that we changed. we just
* print if it's dirty or not. so it tells us: "I'm clean, nobody has
* changed my attributes at all.
*/
$role = Role::findOrFail(1);
return $role->isDirty();
/**
* lets say We fetched this role with id=1 and its status was 1. what
* this returns is still false, because even though we set the status
* attribute equal to 1, we still didn't change it. It was 1 when we
* received it from the database and it's still 1.
*/
$role = Role::findOrFail(1);
$role->status = 1;
return $role->isDirty();
/**
* now if the status was 1 in the db, and we set it to 2, it will
* print the true.
*/
$role = Role::findOrFail(1);
$role->status = 2;
return $role->isDirty();
您还可以将参数传递给isDirty()
仅检查该特定列值的函数。
推荐阅读
- android - Android WebRTC 从 javascript PeerJS 浏览器接收 JSON
- c# - ASP.NET Core:创建和打开 PDF(在浏览器中)
- java - 冒泡排序自适应(java)
- deployment - CMake包(Cpack)——自动添加依赖
- html - 如何使多个容器的高度与高度相同:自动
- jmeter - 在 Jmter 中同时发送相同的 HTTP 请求
- cron - 哪个是访问也有 UI 的 REST 端点的最佳作业调度程序?
- python - 检查路径在文件列表中是否有重复项?
- c# - C# 颜色不匹配,即使它相同
- jelastic - 如何将共享负载均衡器 http/https 端口指向我的 Jelastic Docker 容器的特定端口