Checking for the Unique Column except the Own Column - php

Here is my Rule :
Table Name is : company_info
I have only two fields CompanyID and Telephone
In the update section, i want to check whether the Telephone Number exists for other columns and if the own field have it i don't want to check it. (Currently it checks the own data and returning with Telephone number was taken already).
'Telephone' => 'unique:company_info',
Then i tried with the below rule
But i miss in the
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid)
or
'Telephone' => 'unique|unique:company_info,Telephone,'.$companyid)
or
'Telephone' => 'unique|unique:company_info,Telephone,'.$Telephone)
Here is my Code :
$companyid = Input::get('CompanyID');
$Telephone = Input::get('Telephone');
$rule = array(
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid
)
$validator = Validator::make($data,$rule);
if ($validator->fails())
{
$messages = $validator->messages();
return "0"."||".$messages = $validator->messages()->first('Telephone');
}
While the update query i need to check for the unique rule except the given id
I refered this one http://laravel.com/docs/4.2/validation#rule-unique
But i am not getting return on $validator = Validator::make($data,$rule);
How can i check for the unique value except the own column

I believe you have the wrong syntax for unique validation
it should be
'Telephone' => 'unique:company_info,CompanyID,'.$companyid
or
'Telephone' => 'required|unique:company_info,CompanyID,'.$companyid
and not
'Telephone' => 'unique|unique:company_info,CompanyID,'.$companyid

Can try this as the Laravel Validation provides us various features
$companyid = Input::get('CompanyID');
$Telephone = Input::get('Telephone');
$data = array('companyid'=>$companyid, 'Telephone'=>$Telephone );
//FOR INSERTING NEW DATA
$rule = array(
'Telephone' => 'required|unique:company_info,Telephone,{:id}'
);
$validator = Validator::make($data,$rule);
//FOR UPDATING AN EXISTING DATA
public static function rule ($id, $merge=[]) {
return array_merge(
[
'Telephone' => 'required|unique:company_info,Telephone,'.$id,
],
$merge);
}
$validator = Validator::make($data,self::rule($id));
Comment for errors...

Try following code
'Telephone' => 'unique:company_info,Telephone,'.$companyid.', CompanyID';
{rule} =>
'unique:{table_name},{unique_column_name},{except_column_value},{except_column_name}'

Related

Validate array if already exists in mysql php laravel

Currently I have set of array.
and
I can easily insert these data to my database using Laravel without doing any validations
here's the sample array
CODE:
$excel1 = Importer::make('Excel');
$excel1->hasHeader(true);
$excel1->load($savePath.$fileName);
$excel1->setSheet(2);
$collection1 = $excel1->getCollection();
$arr1 = json_decode($collection1,true);
foreach ($arr1 as $row1) {
$insert_data1[] = array(
'projCode' => $projCode,
'emp_id' => $row1['company_id'],
'type' => 'EMP',
'deleted' => 0,
'by_id' => auth()->user()->id,
'updated_by' => auth()->user()->name,
'created_at' => now(),
'updated_at' => now(),
);
}
dd($insert_data1);
OUTPUT:
and I'm using this code to insert these data to my table
DB::table('tbl_emp_proj')->insert($insert_data1);
and this works fine but the problem is,
I'm trying to validate if emp_id exists or not in my users table
Here's my users table
The value of emp_id from array should check if it already exists in my users using company_id field from users. How can I validate it if $insert_data1 is an array and should be check if it exists on database?
UPDATE
currently i have this validator and I tried to add up the $Insert_data1 but gives me undefined var for $insert_data1.
$validator = Validator::make(
[
'file' => $request->file,
'extension' => strtolower($request->file->getClientOriginalExtension()),
],
[
'file' => 'required|max:5000',
'extension' => 'required|in:,csv,xlsx,xls',
],
$insert_data1,
[
'*.emp_id' => "required|exists:users,company_id",
]
);
You can use Laravel Validator to validate any arrays as if its a request input.
use Illuminate\Support\Facades\Validator;
$validator = Validator::make(
$insert_data1,
[
'*.emp_id' => "required|integer|exists:users,company_id",
]
);
EDIT:
You can receive error messages and error items with the validator APIs.
$failed = $validator->fails(); //boolean
$errors = $validator->errors();
$validated = $validator->validated();
$invalid = $validator->invalid();

Laravel 5 & validating multiple email addresses in a single field

I know in Laravel you can setup validation rules for input fields, for example:
$return = [
'first_name' => 'required|max:300|min:3',
'last_name' => 'required|max:300|min:3',
'email' => 'required|email,
];
Is there a way to easily set this kind of validation for a single field with comma separated email addresses (test#email.com, wibble#test.com) or do I need to manually validate these by splitting them apart and checking each email address individually?
This may be what you are looking for:
$rules = array(
'email_addresses' => 'required',
'email_addresses.*' => 'email'
);
$messages = array(
'email_addresses.required' => 'Email Addresses Required',
'email_addresses.email' => ''
);

How can validate only a certain fields in php Laravel 5?

I'm currently working on my Edit form in my Laravel application.
I request all the inputs from a form submit. I got :
array:6 [▼
"_method" => "PUT"
"_token" => "iWyonRYFjF15wK8fVXJiTkX09YSPmXukyGbBcHRA"
"phone" => "9786770863"
"email" => "test#sites.com1"
"address" => "23 School St Lowell MA 01851"
"$id" => "1"
]
My goal is to only validate only : phone, email, and address.
I've tried
$validator = Validator::make(
['phone' => 'max:20'],
['email' => 'required|email|unique:users,email,'. $id ],
['address' => 'max:255']
);
// dd(Input::get('email')); // HERE <------ I got the email to display
if ( $validator->fails()) {
return Redirect::to('user/profile/'. $id )->withErrors($validator)->withInput();
} else {
$user = User::findOrFail($id);
$user->phone = Input::get('phone');
$user->email = Input::get('email');
$user->address = Input::get('address');
$user->save();
It keep failing on me and say that
The email field is required.
But if I recall correctly the email field is there.
How can validate only a certain fields in php Laravel 5 ?
It should be :
$validator = Validator::make($input, [
'phone' => 'max:20',
'email' => 'required|email|unique:users,email,'. $id ,
'address' => 'max:255']
);
It thinks you are passing the first line as the data to check, and the second line as the rules for your validation. It doesn't find an email key so it tells you it is required.
Your Validator::make() method call is a bit off.
When using this function, the first parameter is the array of data to validate (your request data), and the second parameter is your array of rules.
Your current code has you passing in three parameters. It is treating ['phone' => 'max:20'] as your data to validate, ['email' => 'required|email|unique:users,email,'. $id ], as your rule, and then ['address' => 'max:255'] as your messages array.
It should be something like this:
$validator = Validator::make(
Input::all(),
[
'phone' => 'max:20',
'email' => 'required|email|unique:users,email,'. $id,
'address' => 'max:255'
]
);

How can we validate multiple fields with one validation in cakePHP 2.0?

how can we check firstname and last name is unique validation in cakePHP ?
record1:
first name :raj
last name: kumar
if we enter same name in input field , it should show validation message "Record alredy Exists".
i know how to validate single field validation.
how to validate that the combination of first_name and last_name is unique?
Please help me in this.
Thanks in Advance
You will want to setup a custom validation rule for testing that the 'full name' is unique. For example, in your model add a new method for validation like this:-
public function validateUniqueFullName(array $data) {
$conditions = array(
'first_name' => $this->data[$this->alias]['first_name'],
'last_name' => $this->data[$this->alias]['last_name']
);
if (!empty($this->id)) {
// Make sure we exclude the current record.
$conditions[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
}
return $this->find('count', array('conditions' => $conditions)) === 0;
}
Then add the new validation rule to the model's $validate property:-
public $validate = array(
'first_name' => array(
'unique' => array(
'rule' => 'validateUniqueFullName',
'message' => 'Not unique'
)
)
);
Where 'rule' => 'validateUniqueFullName' instructs Cake to use the new validation rule to check that the name is unique.
You'll probably want to tweak/improve the above custom rule to meet your exact requirements but it should put you on the right track.
Try this way
public $validate = array(
'facebook_link' => array(
'rule' => array('customValidation','facebook_link'),
'message' => 'Please enter facebook link.'
),
'twitter_link' => array(
'rule' => array('customValidation','twitter_link'),
'message' => 'Please enter twitter link.'
)
);
function customValidation($data , $filed) {
if(empty($data[$filed])) {
return false;
}
return true;
}

laravel update a uique value validation

I have a model with a mobileNumber property. the mobile number is unique and the validation rules are:
public static $rulesForEdit = array(
'firstName' => 'required|min:5',
'lastName' => 'required|min:5',
'mobileNumber' => 'required|min:5|unique:admin,mobileNumber|numeric'
);
when I update the model, I do this:
$data = array('firstName' => Input::get('firstName'),
'lastName' => Input::get('lastName'),
'mobileNumber' => Input::get('mobileNumber')
);
$validation = Validator::make($data, Admin::$rulesForEdit);
if($validation->passes()){
$admin = Admin::find($id);
$admin->firstName = Input::get('firstName');
$admin->lastName = Input::get('lastName');
$admin->mobileNumber = Input::get('mobileNumber');
$admin->update();
return Redirect::to("restaurants/admins/".$admin->id);
}else{
return Redirect::back()->withInput()->withErrors($validation);
}
The problem that I keep getting a validation error message states that : The mobile number has already been taken, which is correct, but the mobile is belongs to the same model that I am updating, there is no other model that took this mobile number, just the one that I want to update. In other words, I am updating the firstname and the last name but not the mobile number,
To force the Validator to ignore unique rule for a given id you may pass the id of that recored which is being validated, for example:
'mobileNumber' => 'required|min:5|numeric|unique:admin,mobileNumber,50'
This, will not check uniqueness of the model if the id is 10, so when you are updating the model you need to pass the id of the current model to ignore the unique rule on this model:
'mobileNumber' => 'required|min:5|numeric|unique:admin,mobileNumber,' . $id
// Replace the Model with the name of your model within the controller
// update method before the validation takes place
Model::$rules['mobileNumber'] = 'required|min:5|numeric|unique:admin,mobileNumber,' . $id;

Categories