我正在尝试创建一个用户管理系统。一切都很好,直到我想实现“编辑用户”部分。通过忽略我的规则中的用户 ID,我成功地避免了唯一用户名和电子邮件字段的“问题”。
问题是,当我尝试将用户更新为不存在的用户名或电子邮件时,一切正常。但是当我试图对已经存在的东西做同样的事情时,我得到一个错误:
SQLSTATE [23000]:完整性约束违规:1062 键“users_username_unique”的重复条目“existing_username_here”
我的规则中已经实现了“唯一”字段,所以我不知道这有什么问题。有没有办法让我捕捉到这个特定的异常并将其展示给用户?有没有办法解决这个问题?我一直在寻找几个小时,我似乎找不到任何有用的东西。
编辑:它似乎试图插入一个新的原始而不是更新现有的......!我不知道为什么会这样。有什么想法吗?
管理员控制器.php
public function update($id)
{
if ( ! $this->validator->isValidForAdminEdit()) {
return Redirect::back()->withErrors($this->validator->errors())->withInput();
}
$user = $this->register->getUserById($id);
$data = [
'id' => $user->id,
'first_name' => Input::get('first_name'),
'email' => Input::get('email'),
'username' => Input::get('username'),
'password' => Input::get('password'),
'activated' => Input::get('activated'),
'assign_role' => Input::get('assign_role')
];
$updatedUser = $this->adminRegister->update($data);
return Redirect::to('admin/users')
->with(['flash_message' => "The user $updatedUser->username has been edited.",
'flash_type' => 'success']);
}
DbAdminRepository.php
public function update(array $data)
{
$user = Register::find($data['id']);
$user->first_name = $data['first_name'];
$user->username = $data['username'];
$user->email = $data['email'];
if (isset($data['password']) && ($data['password'] != "")) {
$user->password = Hash::make($data['password']);
}
$user->activated = (! isset($data['activated']) ? (int)0 : (int)1);
$role = $data['assign_role'];
$user->save(); // THE PROBLEM SEEMS TO BE HERE
$user->roles()->detach();
$user->roles()->attach($role);
return $user;
}
验证器.php
public function isValidForAdminEdit(array $rules = array())
{
// if there are no rules return true.
if(!isset(static::$rules)) return true;
$rules = self::processRules($rules ? $rules : static::$admin_edit_rules);
$validator = V::make($this->attributes, $rules);
if ($validator->fails()) {
$this->errors = $validator->messages();
return false;
}
return true;
}
protected function processRules(array $rules)
{
// get the model's ID.
// If the ID is null, it's a new Model, so let's strip out the id completely.
$id = $this->attributes['id'];
$replacement = $id == null ? "" : "," . $this->attributes['id'];
array_walk($rules, function(&$item) use ($replacement)
{
// Replace placeholders
$item = stripos($item, ',:id:') !== false ? str_ireplace(',:id:', $replacement, $item) : $item;
});
return $rules;
}
public function errors()
{
return $this->errors;
}
用户验证器.php
static $admin_edit_rules = [
'username' => 'Required|Min:3|Max:32|Unique:registers,username,:id:',
'email' => 'Required|Between:3,64|Email|Unique:registers,email,:id:',
'first_name' => 'Required|Min:3|Max:80|Alpha',
'password' =>'AlphaNum|Between:4,20|Confirmed',
'password_confirmation'=>'AlphaNum|Between:4,20',
];