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

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'
]
);

Related

How can i avoid update a password in Laravel when the password input field is left empty?

I got this code in laravel that allows an administrator to update an user's password:
public function editarmembro(Request $dados) {
$validatedData = $dados->validate([
'name' => 'required',
'email' => 'required',
'credencial' => 'required',
]);
$dados = $dados->all();
if (!empty($dados['password'])) {
$dados['password'] = Hash::make($dados['password']);
}
DB::table('users')->where('id', $dados['id'])->update(
[ 'name' => $dados['name'], 'email' => $dados['email'], 'credencial' => $dados['credencial'], 'password' => $dados['password'], 'sobre' => $dados['sobre'], 'updated_at' => Carbon::now(), ]
);
return redirect()->route('membros')->with('mensagemSucesso', 'As informações do membro "'.$dados['name'].'" foram atualizadas com sucesso.');
}
My problem is, if he left the password field blank, i get an error screen saying that the password field cannot be NULL. I want my code to NOT update the password if he left the password field blank, but DO update if he inserts something in password field.
Help, pls.
You can remove it from the $dados array if it's empty:
if (!empty($dados['password']))
$dados['password'] = Hash::make($dados['password']);
else
unset($dados['password']);
or with ternary operator
!empty($dados['password'])? $dados['password'] = Hash::make($dados['password']): unset($dados['password']);
and since all the names of the fields match those of the request and the updated_at field should auto-complete, you don't need to reassemble the array for the update.
DB::table('users')->where('id', $dados['id'])->update($dados);
If you want to reassemble the array anyway, you can do so
$update_dados = [
'name' => $dados['name'],
'email' => $dados['email'],
'credencial' => $dados['credencial'],
'sobre' => $dados['sobre'],
'updated_at' => Carbon::now(),
];
if (!empty($dados['password']))
$update_dados['password'] = Hash::make($dados['password']);
DB::table('users')->where('id', $dados['id'])->update($update_dados);
You just need to merge to the array with all the values (except the password) the password only if exists / is set:
$your_array = [
'name' => $dados['name'],
'email' => $dados['email'],
'credencial' => $dados['credencial'],
'sobre' => $dados['sobre'],
'updated_at' => Carbon::now(),
];
DB::table('users')->where('id', $dados['id'])->update(
empty($dados['password']) ? $your_array : array_merge($your_array, ['password' => $dados['password']])
);

how to change the key of validation error in laravel

I am new to laravel and working on apis, I have made an api in which i have implemented validation.Everything is working fine but i am stuck on a little thing. I want to to change the key name in the validation error. For example For the "unique" validation error. This is what now showing
I want to rename "email"(text) key with "message"(text)
I have tried so many thing in illuminate/support/validation.php
messagebag.php file but if it changes then error show of "data undefined".
The links i followed are
https://stillat.com/blog/2018/04/21/laravel-5-message-bags-adding-messages-to-the-message-bag-with-add
https://laracasts.com/discuss/channels/laravel/custom-validation-message-for-array-using-different-key?page=0
Override laravel validation message
This is the validation code
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'fcm_token' => 'required',
'password' => 'required',
'c_password' => 'required|same:password'
]);
You can manually loop over the error MessageBag and construct the response to replace a key
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'fcm_token' => 'required',
'password' => 'required',
'c_password' => 'required|same:password'
]);
$errors = [];
foreach ($validator->errors()->messages() as $key => $value) {
if($key == 'email')
$key = 'message';
$errors[$key] = is_array($value) ? implode(',', $value) : $value;
//implode is for when you have multiple errors for a same key
//like email should valid as well as unique
}
$result = array("status" => count($errors)?0:1, 'data'=>$errors);
return $result;
In resources - lang - en (Or Any Langauge) - validation.php
Put This code in bottom:
'attributes' => [
'email' => 'The Email',
],
In order to change the key of the error message of a certain field, you can transfer the validation of this particular field from the request to the controller (or service). This way you can throw an error with any name you want.
For example:
if (#your validation of the field failed#) {
throw ValidationException::withMessages(['your_key' => 'your message']);
}
And don't forget this line:
use Illuminate\Validation\ValidationException;
The error now will look like this:
{
"message": "The given data was invalid.",
"errors": {
"your_key": [
"your message"
]
}
}
if I understand the problem well. This will help you:
a https://laravel.com/docs/7.x/validation#rule-unique
In your case:
'email' => 'required|email|unique:users,message'
unique:table,column,except,idColumn
Hope it helps.
In Laravel, you can try and validate your email this way:
'email'=>'required|email'

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 validator with a wildcard

i want to make a laravel validator that validates the the fields inside an un-named array ( 0,1,2,3 ) that is inside an array
so my array is like
array [ //the form data
"items" => array:2 [ //the main array i want to validate
0 => array:2 [ // the inner array that i want to validate its data
"id" => "1"
"quantity" => "1000"
]
1 => array:2 [
"id" => "1"
"quantity" => "1000"
]
// other fields of the form,
]
]
so what i want is something like
$validator = Validator::make($request->all(), [
'items.*.id' => 'required' //notice the star *
]);
Laravel 5.2
The syntax in the question is now supported
http://laravel.com/docs/master/validation#validating-arrays
Laravel 5.1
First create the validator with all of your other rules. Use the array rule for items
$validator = Validator::make($request->all(), [
'items' => 'array',
// your other rules here
]);
Then use the Validator each method to apply a set of rules to every item in the items array.
$validator->each('items', [
'id' => 'required',
'quantity' => 'min:0',
]);
This will automatically set these rules for you...
items.*.id => required
items.*.quantity => min:0
https://github.com/laravel/framework/blob/5.1/src/Illuminate/Validation/Validator.php#L261
You could simply do something like that:
$rules = [];
for($i = 0; $i < 10; $i++) {
$rules["items.$i.id"] = "required";
}
$validator = \Validator::make($request->all(), $rules);

Checking for the Unique Column except the Own Column

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}'

Categories