how to change the key of validation error in laravel - php

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'

Related

Manual Laravel Validation using array index (not keys)

A newbie here in terms of Laravel validation - I've searched and checked the manual but can't seem to find an answer to this. I'm using Laravel 8.0.
As per the Laravel manual I have created a manual validation to validate my array, it contains data similar to the below:
$row = array('John','Doe','john.doe#acme.com','Manager');
Because the array has no keys, I can't work out how to reference the array items using their index when creating the Validator, I've tried this:
$validatedRow = Validator::make($row, ['0' => 'required|max:2', '1' => 'required']);
$validatedRow = Validator::make($row, [0 => 'required|max:2', 1 => 'required']);
$validatedRow = Validator::make($row, [$row[0] => 'required|max:2', $row[0] => 'required']);
But no luck - does anyone have any suggestions?
Use Validator
use Illuminate\Support\Facades\Validator;
Then Update your code
$row = array('John','Doe','john.doe#acme.com','Manager');
$rule = [
'0' => 'required|string',
'1' => 'required',
'2' => 'required|email',
'3' => 'required'
];
$validator = Validator::make($row, $rule);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()->all()], 422);
}else{
echo 'ok';
}

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

Handle validator to return json

Laravel throw an exception at $validator->fails() call.
Ok, I just want to create a stateless register method in ApiController.php with Laravel 5.7.
I used the Validator facade to check the sent data.
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()],
Response::HTTP_UNAUTHORIZED);
}
But, when I use xdebug, I see something strange. The fails methods seems throw an exception.
Laravel send an error HTML page with title:
Validation rule unique requires at least 1 parameters.
The route is used in api.php
Route::post('register', 'Api\UserController#register');
Do you have an explanation for this?
Thx for reading.
The syntax for unique rule is unique:table,column,except,idColumn.
So i changed it for you to use the users table.
If you don't want to use the users table change the users part behind unique:
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()],
Response::HTTP_UNAUTHORIZED);
}
For more information on the unique rule see this: https://laravel.com/docs/5.7/validation#rule-unique
In your API request add the following header:
...
Accept: application/json // <-----
This will tell Laravel that you want a response in a json format.
Note: this is different to the Content-type: application/json. The later indicates the format of the data tha is being sent in the body.

Validation on custom array - Lumen

How can I perform validation on custom array in Lumen framework. e.g:
Example array:
$params = array('name' => 'john', 'gender' => 'male');
I have tried something like this but didn;t work:
$validator = Validator::make($params, [
'name' => 'required',
'gender' => 'required'
]);
if ($validator->fails()) {
$messages = $validator->errors();
$message = $messages->first();
echo $message;
exit;
}
The validation is passing because the fields are in fact present. Use something like min or maxor size to validate the length of a string.
http://lumen.laravel.com/docs/validation#rule-required
Edit
I stand corrected. The required does actually seem to validate if it contains anything.
Update
To clarify; the code that is supposed to run if $validator->fails() doesn't ever run if the validation passes.

Laravel if field required, don't return error for each value?

I have a very large registration form.
'username_c' => 'required|unique:contacts_cstm',
'password' => 'required|min:6',
'email' => 'required|email',
'password_repeat' => 'required|same:password',
'first_name' => 'required',
'last_name' => 'required',
'rsa' => 'required',
And so on (another 15 fields)...
The problem is if the form is submitted with nothing entered, about 20 different errors are returned (as they should be).
Except, it would be nice if any of the required fields is NOT entered, to spit back one error saying "All fields are required" or something similar.
I've read through Laravel's docs. on this and didn't find anything. Is there any easy way to do this?
Assuming that all of your fields in the $rules array are required, you should be able to do something as simple as an array_filter($required_fields_input), compare the length against that of your $required_rules and redirect back with a single error message/alert.
See code example below. I tried to keep it simple/commented enough...
Not tested at all ... but theoretically! .... ;)
class YourController {
// ...
public function postFormData()
{
$rules = [
// ...
'first_name' => 'required',
'last_name' => 'required',
'rsa' => 'required'
// ...
];
// Assuming all fields in $rules are "required"
$required_fields = array_keys($rules);
$required_fields_input = Input::only($required_fields);
// Clean out all empty/null fields
$input_not_empty = array_filter($required_fields_input);
if (count($input_not_empty) < count($required_fields))
{
$fill_them_all_in_message = "Please fill in all required fields.";
return Redirect::back()->withMessage($fill_them_all_in_message);
}
/**
* All required fields present
* Continue as usual ..
* .. Validate/Respond/etc...
*/
}
//...
}
I think that pretty much covers your main concern of
a.) Avoiding 15 messages that say "XYZ field is required" ....
b.) Still allowing for the rest of the validation/processing to continue as usual.
Hope that helps!

Categories