Laravel 'sometimes' validator fails with nested arrays - php

Am using the Laravel Validator class to do some basic validation on an array.
My array :
$employee['name']='name';
$employee['address']='address';
$employee['department']['department_name']='deptname';
$employee['department']['department_address']='deptaddress';
I have the validation rules as below:
$rules = array(
'name'=> 'required',
'address' => 'required',
'department.department_name' => 'sometimes|required'
)
And the custom messages as below :
$messages = array(
'name.required' => 'Employee Name is required',
'address.required' => 'Address is required'
'department.department_name.required' => 'Department name is required'
)
I will use Validator::make($employee, $rules, $messages);
As per my rules, department_name should be validated if and only if it is present in the array. But currently the Validator is not validating department_name when its present and blank. Any ideas what I might be doing wrong?

You are going a bit wrong here see the docs here
it is mentioned there If I have $photos['profile'] then my validation will go like this
$validator = Validator::make($request->all(), [
'photos.profile' => 'required|image',
]);
From the above example, In your case it should be like this
$rules = array(
'name'=> 'required',
'address' => 'required',
'employee.department.department_name' => 'sometimes|required'
)
Since you have array like this $employee['department']['department_name']
So does the $message will go like this
$messages = array(
'name.required' => 'Employee Name is required',
'address.required' => 'Address is required'
'employee.department.department_name.required' => 'Department name is required'
)

Related

How can I set custom validation error messages from a controller, in Laravel 8?

I am working on a registration form with Laravel 8 and Sanctum.
I have this piece of code in the AuthController to validate the form fields:
public function register(Request $request) {
$fields = $request->validate([
'first_name' => 'required|string,',
'last_name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed',
'accept' => 'accepted',
]);
// More code here
}
I want to display more user-friendly validation error messages.
Rather than changing the validation.php file (resources\lang\en\validation.php), I want to change the set them for the registration form only, in the method above.
The problem
As someone that has used Codeigniter for a long time, I had, in Codeigniter, the posibility to do just that:
$this->form_validation->set_rules('first_name', 'First name', 'required', array('required' => 'The "First name" field is required'));
I was unable to do something similar in Laravel 8.
How do I get the desired result in Laravel 8?
Maybe this can work for ya.
$rules = [
'first_name' => 'required|string,',
'last_name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed',
'accept' => 'accepted'
];
$customMessages = [
'required' => 'The :attribute field is required.'
];
$this->validate($request, $rules, $customMessages);
Also check out the laravel customizing error messages documentation.
The validate function excepts 3 parameters. A) request, B) the rules, C) Custome Messages.
$this->validate($request, $rules, $customMessages); It means define your custom Message Array by key value. Key is the rulename like require. For example:
[
'required' => 'The :attribute is really,really, really required if you use Login!'
'email.required' => 'Without email you dont come in ;-)'
]

Laravel : Validation messages for custom rule

I am trying to add a custom validation message using the below code,
$validator = Validator::make(
$user,
[
'first_name' => 'required|min:2',
'email' => [
'required',
'email',
Rule::notIn(array_column(Customer::getEmails(), 'email'))
]
],
['email.required' => 'Email is required (Custom message)']);
I have added a custom message for email required validation. No issues there.
For Rule::notIn validation, currently it is returning The email is invalid. How can I add a custom message in this case?
Unable to find anything related in Laravel docs about this.
Try this:
$validator = Validator::make(
$user,
[
'first_name' => 'required|min:2',
'email' => [
'required',
'email',
Rule::notIn(array_column(Customer::getEmails(), 'email'))
]
],
[
'email.required' => 'Email is required (Custom message)',
'email.email' => 'Your custom message here',
'email.not_in' => 'Your custom message here',
]
);

Laravel: Handle unique on Update

I'm using the validation for the employee records during an update. There are some fields which should be unique. But during an update of the employee records, the validation for the unique field is being done. I have researched and tried out the solution as well.
But I'm getting this error:
Error Code : 904 Error Message : ORA-00904: "ID": invalid identifier
Position : 71 Statement : select count() as aggregate from
"EMPLOYEES" where " EMAIL" = :p0 and "ID" <> :p1 Bindings :
[ad#sdfdsf.com,3336] (SQL: select count() as aggregate from
"EMPLOYEES" where " EMAIL" = ad#sdfdsf.com and "ID" <> 3336)
Here is my attempt for the solution:
public function update(Request $request, int $employee_id) {
$this->validate ( $request, [
'first_name' => "required|max:220|regex:/[a-z]/",
'middle_name' => "max:120",
'last_name' => "required|max:220|regex:/[a-z]/",
'email' => "required|unique:employees, email, $employee_id|regex:/[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/",
'home_phone' => "unique:employees,home_phone, $employee_id|numeric|regex:/^[09][0-9]{8,9}$/",
'mobile' => "unique:employees,mobile, $employee_id|numeric|regex:/(9)[0-9]{9}/",
'job_id' => 'required',
'department_id' => 'required',
'group_id' => 'required',
'node' => 'required',
'branch' => 'required',
'username' => "required|unique:employees,username, $employee_id|regex:/[A-Za-z0-9][.][A-Za-z0-9]/",
'exchange_username' => "required|unique:employees,exchange_username, $employee_id|regex:/[A-Za-z0-9][.][A-Za-z0-9]/",
'extension' => "unique:employees,extension, $employee_id|numeric|regex:/[0-9]{4}/",
] );
Employee::where ('employee_id', $employee_id )->update ( $request->only ( [
'first_name',
'middle_name',
'last_name',
'email',
'address',
'home_phone',
'mobile',
'job_id',
'department_id',
'group_id',
'branch',
'node',
'name',
'username',
'type',
'exchange_username',
'toggle_ivr_access',
'extension',
'attributed_team',
'cable_team_id',
'disable',
] ) );
Session::flash ( 'message', 'The Employee is Successfully Updated.' );
return redirect ()->route ( 'employees.index' );
}
Forcing A Unique Rule To Ignore A Given ID:
Sometimes, you may wish to ignore a given ID during the unique check.
For example, consider an "update profile" screen that includes the
user's name, e-mail address, and location. Of course, you will want to
verify that the e-mail address is unique. However, if the user only
changes the name field and not the e-mail field, you do not want a
validation error to be thrown because the user is already the owner of
the e-mail address.
To instruct the validator to ignore the user's ID, we'll use the Rule
class to fluently define the rule. In this example, we'll also specify
the validation rules as an array instead of using the | character to
delimit the rules:
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
I figured out the mistake and successfully find out the solution. Here is the working solution in case anyone is facing the similar problem. I had to pass the employee_id of the single user whereas I was passing the employee_id of the multiple users.
public function update(Request $request, int $employee_id) {
$this->validate ( $request, [
'first_name' => "required|max:220|regex:/[a-z]/",
'middle_name' => "max:120",
'last_name' => "required|max:220|regex:/[a-z]/",
'email' => "required|unique:employees,email,".$employee_id.',employee_id|regex:/[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/',
'home_phone' => "unique:employees,home_phone,$employee_id,employee_id|numeric",
'mobile' => "required|unique:employees,mobile,$employee_id,employee_id|numeric",
'job_id' => 'required',
'department_id' => 'required',
'group_id' => 'required',
'node' => 'required',
'branch' => 'required',
'username' => "required|unique:employees,username,".$employee_id.',employee_id|regex:/[A-Za-z0-9][.][A-Za-z0-9]/',
'exchange_username' => "required|unique:employees,exchange_username,".$employee_id.',employee_id|regex:/[A-Za-z0-9][.][A-Za-z0-9]/',
'extension' => "required|unique:employees,mobile,$employee_id,employee_id|numeric|regex:/[0-9]{4}/",
] );
Employee::where ('employee_id', $employee_id )->update ( $request->only ( [
'first_name',
'middle_name',
'last_name',
'email',
'address',
'home_phone',
'mobile',
'job_id',
'department_id',
'group_id',
'branch',
'node',
'name',
'username',
'type',
'exchange_username',
'toggle_ivr_access',
'extension',
'attributed_team',
'cable_team_id',
'disable',
] ) );
Session::flash ( 'message', 'The Employee is Successfully Updated.' );
return redirect ()->route ( 'employees.index' );
}

Getting the index of a list and display in error message during validation in Laravel

I have a validation rule as follows. I'm using the validate method via the ValidateRequests trait.
$this->validate($request, [
'entries' => 'required|max:5',
'entries.*.name' => 'required',
'entries.*.email' => 'required|email',
'entries.*.mobile_number' => 'required'
]);
And these are some sample error messages that I've encountered.
[
'entries.0.name' => ['The entries.0.name is required.'],
'entries.1.email' => ['The entries.1.email must be a valid email address.']
]
Is there a way to modify the message to these by using only the validation.php in modifying such messages?
[
'entries.0.name' => ['Line 0 - The name is required.'],
'entries.1.email' => ['Line 1 - The email must be a valid email address.']
]
If you want to customize the error message then you can do it as:
$validator = Validator::make($request->all(), [
'entries' => 'required|max:5',
'entries.*.name' => 'required',
'entries.*.email' => 'required|email',
'entries.*.mobile_number' => 'required'
]);
$validator->setAttributeNames([
'entries.*.name' => 'name',
'entries.*.email' => 'email',
'entries.*.mobile_number' => 'mobile number'
]);
$errors = $validation->errors()->all();
foreach ($errors as $key => $error) {
$errors[$key] = "Line {$key} - $error";
}
// dd($errors);
if($validation->fails()) {
return redirect()->back()->withErrors($errors());
}

laravel 5.2 set attribute name

How i set custom the attributte names in laravel 5.2 I already try this code, but doesn't work:
$attNames = array(
'code' => 'Número',
'contributor' => 'Nº Contribuinte',
'create_date' => 'Data criação',
'address' => 'Morada',
'zip_code' => 'Cod. Postal',
'city' => 'Localidade',
'email' => 'E-mail',
'phone_number' => 'Telefone',
'note' => 'Observações',
);
$validator = Validator::make($client, $this->rules,[],$attNames);
$validator->setAttributeNames($attNames);
if ($validator->fails()) {
// send back to the page with the input data and errors
$errors = $validator->messages();
return Redirect::to('/client/create')->withInput()->withErrors($errors);
}
You have passed wrong arguments to Validator::make.
You can pass only three arguments.
As per Documentation,
If needed, you may use custom error messages for validation instead of
the defaults. There are several ways to specify custom messages.
First, you may pass the custom messages as the third argument to the
Validator::make method.
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
I figure out.
controller:
use Validator;
(...)
$attName=array(
'code' => trans('validation.code'),
'contributor' => trans('validation.contributor'),
'create_date' => trans('validation.create_date'),
'address' => trans('validation.address'),
'zip_code' => trans('validation.zip_code'),
'city' => trans('validation.city'),
'email' => trans('validation.email'),
'phone_number' => trans('validation.phone_number'),
'note' => trans('validation.note'),
);
$validator = Validator::make($client, $this->rules, [], $attNames);
validation.php:
'attributes' => [
'code' => 'número',
'contributor' => 'nº contribuinte',
'create_date' => 'data criação',
'address' => 'morada',
'zip_code' => 'cod. postal',
'city' => 'localidade',
'email' => 'e-mail',
'phone_number' => 'telefone',
'note' => 'observações',
],

Categories