我有一个laravel User
模型,该模型在username
和email
上有唯一的验证规则。在我的存储库中,当我更新模型时,我重新验证字段,以便不会出现所需规则验证的问题:
public function update($id, $data) {
$user = $this->findById($id);
$user->fill($data);
$this->validate($user->toArray());
$user->save();
return $user;
}
使用
进行测试失败ValidationException: {"username":["The username has already been taken."],"email":["The email has already been taken."]}
有没有办法优雅地解决这个问题?
答案 0 :(得分:113)
将当前正在更新的实例的id
附加到验证器。
传递您实例的id
以忽略唯一验证器。
在验证程序中,使用参数检测您是更新还是创建资源。
如果要更新,请强制使用唯一规则忽略给定的ID:
//rules
'email' => 'unique:users,email_address,' . $userId,
如果正在创建,请照常进行:
//rules
'email' => 'unique:users,email_address',
答案 1 :(得分:27)
另一种优雅的方式......
在模型中,创建一个静态函数:
public static function rules ($id=0, $merge=[]) {
return array_merge(
[
'username' => 'required|min:3|max:12|unique:users,username' . ($id ? ",$id" : ''),
'email' => 'required|email|unique:member'. ($id ? ",id,$id" : ''),
'firstname' => 'required|min:2',
'lastname' => 'required|min:2',
...
],
$merge);
}
创建验证:
$validator = Validator::make($input, User::rules());
更新验证:
$validator = Validator::make($input, User::rules($id));
更新验证,以及一些其他规则:
$extend_rules = [
'password' => 'required|min:6|same:password_again',
'password_again' => 'required'
];
$validator = Validator::make($input, User::rules($id, $extend_rules));
尼斯。
答案 2 :(得分:8)
在我的问题中工作:
public function update($id, $data) {
$user = $this->findById($id);
$user->fill($data);
$this->validate($user->toArray(), $id);
$user->save();
return $user;
}
public function validate($data, $id=null) {
$rules = User::$rules;
if ($id !== null) {
$rules['username'] .= ",$id";
$rules['email'] .= ",$id";
}
$validation = Validator::make($data, $rules);
if ($validation->fails()) {
throw new ValidationException($validation);
}
return true;
}
是我所做的,基于上面接受的答案。
编辑:使用表单请求,一切都变得更简单:
<?php namespace App\Http\Requests;
class UpdateUserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|unique:users,username,'.$this->id,
'email' => 'required|unique:users,email,'.$this->id,
];
}
}
您只需将UpdateUserRequest传递给更新方法,并确保POST模型ID。
答案 3 :(得分:3)
Laravel 5兼容且通用的方式:
我遇到了同样的问题,并以通用的方式解决了这个问题。如果您创建项目,则使用默认规则,如果您更新项目,它将检查您的:unique
规则并自动插入排除(如果需要)。
创建一个BaseModel
类,让所有模型继承它:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model {
/**
* The validation rules for this model
*
* @var array
*/
protected static $rules = [];
/**
* Return model validation rules
*
* @return array
*/
public static function getRules() {
return static::$rules;
}
/**
* Return model validation rules for an update
* Add exception to :unique validations where necessary
* That means: enforce unique if a unique field changed.
* But relax unique if a unique field did not change
*
* @return array;
*/
public function getUpdateRules() {
$updateRules = [];
foreach(self::getRules() as $field => $rule) {
$newRule = [];
// Split rule up into parts
$ruleParts = explode('|',$rule);
// Check each part for unique
foreach($ruleParts as $part) {
if(strpos($part,'unique:') === 0) {
// Check if field was unchanged
if ( ! $this->isDirty($field)) {
// Field did not change, make exception for this model
$part = $part . ',' . $field . ',' . $this->getAttribute($field) . ',' . $field;
}
}
// All other go directly back to the newRule Array
$newRule[] = $part;
}
// Add newRule to updateRules
$updateRules[$field] = join('|', $newRule);
}
return $updateRules;
}
}
您现在可以像以前一样在模型中定义规则:
protected static $rules = [
'name' => 'required|alpha|unique:roles',
'displayName' => 'required|alpha_dash',
'permissions' => 'array',
];
并在您的控制器中验证它们。如果模型未验证,它将自动重定向回具有相应验证错误的表单。如果没有发生验证错误,它将继续执行代码。
public function postCreate(Request $request)
{
// Validate
$this->validate($request, Role::getRules());
// Validation successful -> create role
Role::create($request->all());
return redirect()->route('admin.role.index');
}
public function postEdit(Request $request, Role $role)
{
// Validate
$this->validate($request, $role->getUpdateRules());
// Validation successful -> update role
$role->update($request->input());
return redirect()->route('admin.role.index');
}
那就是它! :)请注意,在创建时,我们会调用Role::getRules()
,然后在编辑时调用$role->getUpdateRules()
。
答案 4 :(得分:3)
Laravel中具有不同列ID的唯一验证
'UserEmail'=>"required|email|unique:users,UserEmail,$userID,UserID"
答案 5 :(得分:2)
我有BaseModel类,所以我需要更通用的东西。
//app/BaseModel.php
public function rules()
{
return $rules = [];
}
public function isValid($id = '')
{
$validation = Validator::make($this->attributes, $this->rules($id));
if($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
在用户类中,假设我只需要验证电子邮件和名称:
//app/User.php
//User extends BaseModel
public function rules($id = '')
{
$rules = [
'name' => 'required|min:3',
'email' => 'required|email|unique:users,email',
'password' => 'required|alpha_num|between:6,12',
'password_confirmation' => 'same:password|required|alpha_num|between:6,12',
];
if(!empty($id))
{
$rules['email'].= ",$id";
unset($rules['password']);
unset($rules['password_confirmation']);
}
return $rules;
}
我用phpunit测试了这个并且运行正常。
//tests/models/UserTest.php
public function testUpdateExistingUser()
{
$user = User::find(1);
$result = $user->id;
$this->assertEquals(true, $result);
$user->name = 'test update';
$user->email = 'ddd@test.si';
$user->save();
$this->assertTrue($user->isValid($user->id), 'Expected to pass');
}
我希望能帮助某人,即使是为了获得更好的主意。感谢您分享您的。 (在Laravel 5.0上测试)
答案 6 :(得分:2)
或者您在表单请求中可以做的是(对于Laravel 5.3 +)
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'.$this->user, //here user is users/{user} from resource's route url
];
}
我已经在Laravel 5.6中做到了,并且奏效了。
答案 7 :(得分:2)
角色更新的简单示例
// model/User.php
class User extends Eloquent
{
public static function rolesUpdate($id)
{
return array(
'username' => 'required|alpha_dash|unique:users,username,' . $id,
'email' => 'required|email|unique:users,email,'. $id,
'password' => 'between:4,11',
);
}
}
// controllers/UsersControllers.php
class UsersController extends Controller
{
public function update($id)
{
$user = User::find($id);
$validation = Validator::make($input, User::rolesUpdate($user->id));
if ($validation->passes())
{
$user->update($input);
return Redirect::route('admin.user.show', $id);
}
return Redirect::route('admin.user.edit', $id)->withInput()->withErrors($validation);
}
}
答案 8 :(得分:1)
我遇到了同样的问题。 我做了什么:在我的视图中添加一个带有模型id的隐藏字段,并在验证器中检查唯一,只有我从视图中获得了一些id。
$this->validate(
$request,
[
'index' => implode('|', ['required', $request->input('id') ? '' : 'unique:members']),
'name' => 'required',
'surname' => 'required',
]
);
答案 9 :(得分:1)
如果你有另一个列被用作外键或索引,那么你必须在规则中指定这一列。
'phone' => [
"required",
"phone",
Rule::unique('shops')->ignore($shopId, 'id')->where(function ($query) {
$query->where('user_id', Auth::id());
}),
],
答案 10 :(得分:1)
您可以尝试下面的代码
return [
'email' => 'required|email|max:255|unique:users,email,' .$this->get('id'),
'username' => 'required|alpha_dash|max:50|unique:users,username,'.$this->get('id'),
'password' => 'required|min:6',
'confirm-password' => 'required|same:password',
];
答案 11 :(得分:1)
'email' => [
'required',
Rule::exists('staff')->where(function ($query) {
$query->where('account_id', 1);
}),
],
'email' => [
'required',
Rule::unique('users')->ignore($user->id)->where(function ($query) {
$query->where('account_id', 1);
})
],
答案 12 :(得分:1)
public static function custom_validation()
{
$rules = array('title' => 'required ','description' => 'required','status' => 'required',);
$messages = array('title.required' => 'The Title must be required','status.required' => 'The Status must be required','description.required' => 'The Description must be required',);
$validation = Validator::make(Input::all(), $rules, $messages);
return $validation;
}
答案 13 :(得分:1)
我正在为Store和Update调用不同的验证类。在我的情况下,我不想更新每个字段,因此我有创建和编辑的公共字段的baseRules。为每个添加额外的验证类。我希望我的例子很有帮助。我正在使用Laravel 4。
型号:
public static $baseRules = array(
'first_name' => 'required',
'last_name' => 'required',
'description' => 'required',
'description2' => 'required',
'phone' => 'required | numeric',
'video_link' => 'required | url',
'video_title' => 'required | max:87',
'video_description' => 'required',
'sex' => 'in:M,F,B',
'title' => 'required'
);
public static function validate($data)
{
$createRule = static::$baseRules;
$createRule['email'] = 'required | email | unique:musicians';
$createRule['band'] = 'required | unique:musicians';
$createRule['style'] = 'required';
$createRule['instrument'] = 'required';
$createRule['myFile'] = 'required | image';
return Validator::make($data, $createRule);
}
public static function validateUpdate($data, $id)
{
$updateRule = static::$baseRules;
$updateRule['email'] = 'required | email | unique:musicians,email,' . $id;
$updateRule['band'] = 'required | unique:musicians,band,' . $id;
return Validator::make($data, $updateRule);
}
控制器: 存储方式:
public function store()
{
$myInput = Input::all();
$validation = Musician::validate($myInput);
if($validation->fails())
{
$key = "errorMusician";
return Redirect::to('musician/create')
->withErrors($validation, 'musicain')
->withInput();
}
}
更新方法:
public function update($id)
{
$myInput = Input::all();
$validation = Musician::validateUpdate($myInput, $id);
if($validation->fails())
{
$key = "error";
$message = $validation->messages();
return Redirect::to('musician/' . $id)
->withErrors($validation, 'musicain')
->withInput();
}
}
答案 14 :(得分:0)
对于自定义FormRequest和Laravel 5.7+,您可以像这样获取更新后的模型的ID:
public function rules()
{
return [
'name' => 'required|min:5|max:255|unique:schools,name,'.\Request::instance()->id
];
}
答案 15 :(得分:0)
Laravel 5.8简单
您可以很好地在表单请求中完成所有操作。 。 。
首先创建一个字段,您可以通过该字段以常规编辑形式传递ID(不可见)。即
<div class="form-group d-none">
<input class="form-control" name="id" type="text" value="{{ $example->id }}" >
</div>
... 然后确保将Rule类添加到表单请求中,如下所示:
use Illuminate\Validation\Rule;
...添加唯一规则,忽略当前ID,如下所示:
public function rules()
{
return [
'example_field_1' => ['required', Rule::unique('example_table')->ignore($this->id)],
'example_field_2' => 'required',
];
...最后,以与存储方法相同的方式在update方法中键入提示表单请求,如下所示:
public function update(ExampleValidation $request, Examle $example)
{
$example->example_field_1 = $request->example_field_1;
...
$example->save();
$message = "The aircraft was successully updated";
return back()->with('status', $message);
}
这样,您就不会不必要地重复代码:-)
答案 16 :(得分:0)
public function rules()
{
if ($this->method() == 'PUT') {
$post_id = $this->segment(3);
$rules = [
'post_title' => 'required|unique:posts,post_title,' . $post_id
];
} else {
$rules = [
'post_title' => 'required|unique:posts,post_title'
];
}
return $rules;
}
答案 17 :(得分:0)
适用于使用 Form请求
的任何人在我的情况下,我尝试了以下所有方法,但都不起作用:
$this->id
,$this->user->id
,$this->user
。
这是因为我无法直接访问模型$id
或$id
。
所以我从查询中使用要验证的相同$id
字段获得了unique
:
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$id = YourModel::where('unique_field',$this->request->get('unique_field'))->value('id');
return [
'unique_field' => ['rule1','rule2',Rule::unique('yourTable')->ignore($id)],
];
}
答案 18 :(得分:0)
它会 100% 工作 我有两个案例实现,比如一个案例是数据库表产品中的相同表单字段,另一个是 products_name 是表单字段,在表中,它的名称是名称,我们如何在更新时验证和忽略该 ID。我已经加密了,所以我解密了 id,如果你是加密的,那么你将解密,否则将传递它,因为它来自表单。
$request->validate([
'product_code' => 'required|unique:products,product_code,'.decrypt($request->hiddenProductId),
'products_name' => 'required|unique:products,name,'.decrypt($request->hiddenProductId),
]);