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',
];
}
Try to put the id of the register in method setId
$this->validator->with($data)->setId($id)->passesOrFail(ValidatorInterface::RULE_UPDATE);
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
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);
Related
I create request in laravel for validation where i have to validate phone number array.How to validate it. Below i am sharing:
Array that i pass in postman is:
{
"name": "test nbame",
"phone_number": {
"number": "+8896 5432",
"internationalNumber": "+852 7896 5432",
"nationalNumber": "+8896 5432",
"e164Number": "+85278965432",
"countryCode": "HK",
"dialCode": "+852"
},
"designation": "xyz"
}
public function rules()
{
return [
'name' => 'required',
'dial_number' => 'required',
'phone_number' => 'required|regex:/(^[0-9 ]+$)+/',
//'image' => 'required',
];
}
how to validate phone_number array.
Based on your json you can do something like below
public function rules()
{
return [
'name' => 'required',
'dial_number' => 'required',
'phone_number' => 'required|array',
'phone_number.number' => 'required|regex:/(^[0-9 ]+$)+/',
'phone_number.internationalNumber' => 'required|regex:/(^[0-9 ]+$)+/',
'phone_number.nationalNumber' => 'required|regex:/(^[0-9 ]+$)+/',
'phone_number.e164Number' => 'required',
'phone_number.countryCode' => 'required|string',
'phone_number.countryCode' => 'required|string',
'phone_number.dialCode' => 'required',
//'image' => 'required',
];
}
for more info you can visit laravel documentation
You're validating against a nested array in Laravel:
public function rules()
{
return [
...
'phone_number.number' => 'required|regex:/(^[0-9 ]+$)+/',
];
}
Read more in the docs.
You will check the number by regex. You will find a lot of variants of possible phone numbers. That means that you need a regex which is very flexible. How flexible the regex should be depends on you. here is an example:
'phone_number.number' => 'required|regex:/(^[0-9 ]+$)+/',
I want to update record but before update i want to check :-
1. if user exists at time not allowed to update.
Example :-
User jay try to update his name, but user insert same name which is already exists in jay field. at time i want to allow user to update but this code give error that username already exists. What i should do ??
Controller :-
public function update_data($update_id){
$gender_list = ['Male', 'Female', 'Other'];
$country_list = ['India', 'US', 'UK', 'Germany', 'Austraila'];
$Validator = $this->validate(request(), [
'username' => 'required|unique:userlists|alpha_num|max:30',
'email' => ['required', 'unique:userlists', 'email', 'regex:/((yahoo|gmail|hotmail)\.com)/'],
'password' => 'required',
'bod' => 'required|after_or_equal:today',
'comments' => 'required',
'phone_no' => 'required|numeric',
'country' => 'required|alpha',
'gender' => 'required',
'agreement' => 'required',
],[
'required' => 'Please Enter Your :attribute',
]);
if(!in_array($request->gender, $gender_list) || !in_array($request->country, $country_list)){
session()->flash('G_msg', 'Hello Hackes Please Go Back');
return back();
}
if($Validator->passes()){
// updation code.
}
}
You can use validation like below:
'username' => ['required','alpha_num', 'max:30',Rule::unique('userlists')->ignore($update_id)]
Make sure Rule is defined above Class:
use Illuminate\Validation\Rule;
try unique
'username' => 'required|unique:table_name,username,' . $update_id . ',user_id',
You may use Rule
use Illuminate\Validation\Rule;
'username' => ['required','alpha_num', 'max:30',Rule::unique('userlists')->ignore($update_id)]
In my laravel application I need to apply the validation rules on conditional bases. For example: In the Store method the password field is required and min chars: 6. But, in Update method password field is not required, however, if the user enters the password then it must be greater than 6 chars.
SomeController.php
private function validations($customRules = [])
{
# variables
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'pword' => 'required|min:6',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
$messages = [
'contact_person.required' => '`<strong class="style-underline">Contact person</strong>` - Required',
'contact_person.min' => '`<strong class="style-underline">Contact person</strong>` - Must be at least :min chars',
'mobile_number.required' => '`<strong class="style-underline">Mobile number</strong>` - Required',
'mobile_number.numeric' => '`<strong class="style-underline">Mobile number</strong>` - Must be a numeric value',
'email.required' => '`<strong class="style-underline">Eamil</strong>` - Required',
'email.email' => '`<strong class="style-underline">Email</strong>` - Must be a valid email address',
'pword.required' => '`<strong class="style-underline">Password</strong>` - Required',
'pword.min' => '`<strong class="style-underline">Password</strong>` - Must have a at least :min characters',
'status.required' => '`<strong class="style-underline">Status</strong>` - Required',
];
if(!empty($customRules))
$rules = \array_merge($rules, $customRules);
# returning
return request()->validate($rules, $messages);
}
After modifying the rules, based on the update method requirement, the pword field is validated for min chars. Which should not happen as the field was left empty.
Currently I am forced to do this.
public function update()
{
...
# validating submitted data
if(!empty(request()->pword))
$this->validations([ 'pword' => 'min:6' ]);
else
$this->validations([ 'pword' => '' ]);
....
}
You can use nullabe instead required, Blank value converted as null if you are using eloquent, because of below middleware
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
So your method would be like
private function validations($request,$update = false){
$rules = [
'contact_person' => 'required|min:2',
'mobile_number' => 'required|numeric',
'pword' => 'nullable|min:6',
'email' => 'required|email',
'address' => 'required',
'status' => 'required',
];
}
In ContactsRequest.php
public function rules()
{
return [
'org_id' => 'required',
'name' => 'required',
'office' => 'required',
'mobile' => 'required_without:home',
'home' => 'required_without:mobile'
];
}
So basically what i want is , i have a form which will be taking the attributes specified in the code. But i want to modify code so that entering either one of 'home' or 'mobile' will allow me to create the new user.
What should be done.Any help would be appreciated
I have a users table which has a unique validate rule on email and username. When i am trying to update not ignore unique validation. Please see my code below.
UserRequest.php
public function rules()
{
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$id,
];
}
Please try this
public function rules()
{
$id = $this->request->get('id') ? ',' . $this->request->get('id') : '';
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$id,
];
}
In laravel 5.5 you should do like this:
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
Check laravel documentaion about rule-unique.
You needed to skip id if you validate for update, like as below
public function rules($id='')
{
$id = $id ? ','.$id.',id':'';
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$id,
];
}
In Laravel docs, you have provide 3rd and 4th param in unique rule
unique:table,column,except,idColumn
You could use something like this:
$id = $this->isMethod('put') ? ',' . auth()->id() : '';
assuming you use put method for update
before line with return
for somebody else faced this issue:
public function rules()
{
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$this->user->id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$this->user->id,
];
}
I fixed this by using this:
public function rules()
{
$id = $this->user->id ?? null;
return [
"name" => "required",
"mobile" => "required",
"email" => "required|unique:users,email, $id",
"usercategory" => "required",
"username" => "required|unique:users,username, $id",
];
}
Note that for other models other than the User model, the user in $this->user->id will be the model name in lowercase