Laravel 5.3 唯一验证
Laravel 5.3 Validation unique
我目前正在努力验证 Laravel,尤其是 unique
验证器。
我有一个table,里面有一些值,现在重要的是templateUrl
。我所做的是,向用户显示一个表单,其中包含他之前(保存后)输入的 templateUrl
和其他一些值,然后他可以更改它或保持原样。这个templateUrl
在这个table中应该是唯一的。因此,如果用户在表单中更改此 templateUrl
,并且尚未使用,一切都很好,但如果用户现在尝试保存它,而不更改 templateUrl
,则验证会抛出错误(因为这已经保存在 table 中,即使它是同一行...)。所以似乎无法保存该值,即使它是同一行和同一列。我希望你明白我的意思吗?
这是验证代码:
$this->validate($request,
[
'templateUrl' => 'required|unique:users'
],
[
'templateUrl.unique' => 'Diese URL ist leider schon vergeben. Bitte suchen Sie sich eine andere aus!'
]
);
我该怎么做才能保存值,如果是同一个用户,那么 "enters" 或者让值保持原样?
当然,没有其他用户应该能够输入相同的 templateUrl
,这就是为什么我需要这样的验证,但是如果用户让 templateUrl
不变并且只是更改表单中的其他字段,当然它应该可以。
有什么想法、技巧吗?
您可以向验证添加额外参数以忽略给定行,在本例中为当前行。有关这方面的更多信息,请参阅 the documentation.
例如:
$this->validate($request,
[
'templateUrl' => 'required|unique:users,templateUrl,' . $user->id // Ignore rows with primary key $user->id
],
[
'templateUrl.unique' => 'Diese URL ist leider schon vergeben. Bitte suchen Sie sich eine andere aus!'
]
);
所以你可以做如下的东西。检查是否仅对其他用户是唯一的,并且仅当找到用户时。这样您就可以在更新和存储方法中使用此方法。无论如何 - 最好将此代码移至 Form Request.
$this->validate($request, [
'templateUrl' => 'required|unique:users,templateUrl' . ($user === null ? '' : ',' . $user->id),
], [
'templateUrl.unique' => 'Diese URL ist leider schon vergeben. Bitte suchen Sie sich eine andere aus!',
]
);
我目前正在努力验证 Laravel,尤其是 unique
验证器。
我有一个table,里面有一些值,现在重要的是templateUrl
。我所做的是,向用户显示一个表单,其中包含他之前(保存后)输入的 templateUrl
和其他一些值,然后他可以更改它或保持原样。这个templateUrl
在这个table中应该是唯一的。因此,如果用户在表单中更改此 templateUrl
,并且尚未使用,一切都很好,但如果用户现在尝试保存它,而不更改 templateUrl
,则验证会抛出错误(因为这已经保存在 table 中,即使它是同一行...)。所以似乎无法保存该值,即使它是同一行和同一列。我希望你明白我的意思吗?
这是验证代码:
$this->validate($request,
[
'templateUrl' => 'required|unique:users'
],
[
'templateUrl.unique' => 'Diese URL ist leider schon vergeben. Bitte suchen Sie sich eine andere aus!'
]
);
我该怎么做才能保存值,如果是同一个用户,那么 "enters" 或者让值保持原样?
当然,没有其他用户应该能够输入相同的 templateUrl
,这就是为什么我需要这样的验证,但是如果用户让 templateUrl
不变并且只是更改表单中的其他字段,当然它应该可以。
有什么想法、技巧吗?
您可以向验证添加额外参数以忽略给定行,在本例中为当前行。有关这方面的更多信息,请参阅 the documentation.
例如:
$this->validate($request,
[
'templateUrl' => 'required|unique:users,templateUrl,' . $user->id // Ignore rows with primary key $user->id
],
[
'templateUrl.unique' => 'Diese URL ist leider schon vergeben. Bitte suchen Sie sich eine andere aus!'
]
);
所以你可以做如下的东西。检查是否仅对其他用户是唯一的,并且仅当找到用户时。这样您就可以在更新和存储方法中使用此方法。无论如何 - 最好将此代码移至 Form Request.
$this->validate($request, [
'templateUrl' => 'required|unique:users,templateUrl' . ($user === null ? '' : ',' . $user->id),
], [
'templateUrl.unique' => 'Diese URL ist leider schon vergeben. Bitte suchen Sie sich eine andere aus!',
]
);