Reputation: 358
I am using the L5 repository and it has the validator package (https://github.com/andersao/laravel-validator) but I am have problems to do the validation of the unique fields on update it, anyone to help me???
******the example bellow I tried in this way on RULE_UPDATE but no success..
((((((FIELDS I WANT TO VALIDATE : people_id, email BECAUSE THESE ARE UNIQUE ONLY FOR REST OF THE USERS, NOT TO THIS CURRENT USER THAT ITS UPDATING )))))))
calling the validation in the UserService.php:
use Prettus\Validator\Contracts\ValidatorInterface;
public __construct(){
$this->validator = \App::make('App\Validators\UserValidator');
}
save($data){
if(!empty($data['id'])){
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_UPDATE);
}else{
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_CREATE);
}
}
namespace App\Validators;
use \Prettus\Validator\Contracts\ValidatorInterface; use \Prettus\Validator\LaravelValidator;
class UserValidator extends LaravelValidator {
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'people_id' => 'required|unique:users',
'active' => 'required',
'available_chat' => 'required',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'masters_id' => 'required',
],
ValidatorInterface::RULE_UPDATE => [
'id' => 'required',
'people_id' => 'required|unique:users,id,:id',
'active' => 'required',
'available_chat' => 'required',
'email' => 'required|string|email|max:255|unique:users,id,:id',
//'password' => 'required|string|min:6|confirmed',
//'masters_id' => 'required',
],
];
protected $messages = [
'id.required' => 'Usuário não encontrado!',
'people_id.required' => 'Pessoa é obrigatório',
'people_id.unique' => 'Pessoa já cadastrada',
'active.required' => 'Obrigatório',
'available_chat.required' => 'Obrigatório',
'email.required' => 'Digite o e-mail',
'password.required' => 'Digite a senha',
'password.min' => 'Digite uma senha com 6 caracteres',
'password.confirmed' => 'Confirme a senha corretamente',
'email.unique' => 'E-mail já cadastrado',
];
}
Upvotes: 1
Views: 1237
Reputation: 529
Try to use the below changes it will work. Add below code in your Validator for check Unique Email validation
ValidatorInterface::RULE_UPDATE => [
'email' => 'required|unique:customers,email,id'
],
After that set id for validation code like this
$this->validator->with($request->all())->setId($id)->passesOrFail(ValidatorInterface::RULE_UPDATE);
Upvotes: 0
Reputation: 371
Try to put the id of the register in method setId
$this->validator->with($data)->setId($id)->passesOrFail(ValidatorInterface::RULE_UPDATE);
Upvotes: 2
Reputation: 15464
While updating you need to force a unique rule to Ignore Given ID
'people_id' => 'required|user,people_id,'.$id
//id is the primary id of the field which you want to update
with unique validation which must be ignored
https://laravel.com/docs/5.2/validation#rule-unique
Upvotes: 2