我正在尝试创建一个用户管理系统。在我想要实现“编辑用户”部分之前,一切都很顺利。通过在规则中忽略用户的ID,我成功地避免了使用唯一用户名和电子邮件字段的“问题”。
问题是,当我尝试将用户更新为不存在的用户名或电子邮件时,一切正常。但是当我试图对已经存在的东西做同样的事情时,我得到一个错误:
SQLSTATE [23000]:完整性约束违规:1062重复条目'users_username_unique'的重复条目'existing_username_here'
我已经在我的规则中实现了“独特”字段,因此我不知道这有什么问题。有没有办法可以捕获这个特定的异常并向用户显示?有没有办法解决这个问题?我一直在寻找数小时,我似乎找不到任何有用的东西。
编辑:它似乎尝试插入新原始而不是更新现有的原始数据......!我不知道为什么会这样。有什么想法吗?
AdminController.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;
}
Validator.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;
}
UserValidator.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',
];