我将username
用作id
进行登录,并将用户名和电子邮件设置为唯一。
每当我输入用户名和电子邮件时,验证规则都会检查即将到来的数据,并且没有问题,因为username
和email
是新的且唯一的。
我更新时会出现问题。更新属性时,不需要主要更改用户名,但是规则要求使用unique, username
。
使用验证规则更新唯一属性的最佳做法是什么?。
更新用户方法
public function updateUser($req, $id)
{
$user = User::where('user_id', $id)->firstOrFail();
$user->username = $req->input('username');
$user->password = Hash::make($req->input('password'));
$user->email = $req->input('email');
$user->first_name = $req->input('first_name');
$user->last_name = $req->input('last_name');
$user->phone = $req->input('phone');
$user->emergency_phone = $req->input('emergency_phone');
$user->profile_photo = $req->input('profile_photo');
$user->role = $req->input('role');
$user->status = $req->input('status');
$user->save();
return $this->filterUsers([$user]);
}
规则
protected $rules = [
'username' => 'required|max:20|unique:users',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required',
// **in Production **
// 'password' => [
// 'required',
// 'min:6',
// 'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/',
// 'confirmed'
// ],
/**
* Three of the five rules.
* English uppercase characters (A – Z)
* English lowercase characters (a – z)
* Base 10 digits (0 – 9)
* Non-alphanumeric (For example: !, $, #, or %)
* Unicode characters
*/
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:5',
'role' => 'required'
];
答案 0 :(得分:1)
At edit time it will check for a unique username so we avoid unique for a current edit id
In the update method your validation rules as per below:
protected $rules = [
'username' => 'required|max:20|unique:users,username,' . $id',
'email' => 'required|string|email|max:255|unique:users,email,' . $id',
'password' => 'required',
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:5',
'role' => 'required'
];
答案 1 :(得分:1)
您可以使用
'username' => 'required|max:20|unique:users,username,' . $id',
如果您的用户表的主键是id
,如果它是user_id
之类的东西,那么它将变成
'username' => 'required|email|unique:user,username,' . $request->input('user_id') . ',userid',
所以语法是
'input_field' => 'unique:<table name>,<column name for this input field>, <unique id>, <unique id column in table>';
答案 2 :(得分:0)
您需要在控制器Use Validator;
中使用laravel验证程序类
并使用类似这样的内容:
$error = Validator::make($req->all(), $rules);
验证文档中的更多示例here。