控制器内
public function store(Request $req)
{
$req->validate([
'username' => 'required|unique:users',
]);
$users = new Users();
$users->username = $req->username;
$users->save();
return redirect()->route('list.users');
}
用户名验证返回为The username has already been taken.
我输入的用户名字段为JHON,我想返回如下验证:The JHON has already been taken.
?
我相信在定义自定义验证消息时可以使用:input
。
public function store(Request $req)
{
Validator::make($req, [
'username' => 'required|unique:users',
], [
'unique' => 'The :input username has already been taken.',
]);
$users = new Users();
$users->username = $req->username;
$users->save();
return redirect()->route('list.users');
}
为了使代码更干净,您应该更改"唯一"验证错误的本地化
转到文件"resources/lang/en/validation.php"(或使用您的语言的iso代码更改"en"部分(并更改"唯一"值。
发件人:
'unique' => 'The :attribute has already been taken.',
收件人:
'unique' => 'The :attribute :input has already been taken.',
这样,您应该得到以下消息
用户名JHON已被占用。
$req->validate([
'username' => 'required|unique:users,username',
]);
这是使用unique的语法:
unique:table,column
https://laravel.com/docs/7.x/validation#rule-唯一