I want to convert laravel validation error array to a comma separated string. This is to use in an api service for an ios application. So that the iOs developer can process error messages easily.
I tried,
$valArr = [];
foreach ($validator->errors() as $key => $value) {
$errStr = $key.' '.$value[0];
array_push($valArr, $errStr);
}
if(!empty($valArr)){
$errStrFinal = implode(',', $valArr);
}
But it is not working.
How do I show laravel validation errors in blade? You can call any() method on $errors variable to check that there are any validation errors exist in it or not. It returns 1 if any errors exist in $errors variable. After that you can call foreach method on $errors->all() and display message using $error variable.
To get the exact words to validate you can make use of Rule::in method available with laravel. Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.
After checking if the request failed to pass validation, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user.
You should do like this :
$errorString = implode(",",$validator->messages()->all());
P.S. Assuming
$validator = Validator::make($dataToBeChecked,$validationArray,$messageArray)
The $validator->errors()
returns a MessageBag
,
see: https://laravel.com/api/5.3/Illuminate/Support/MessageBag.html.
You are close, you need to call the getMessages()
function on errors()
, so:
foreach ($validator->errors()->getMessages() as $key => $value) {
Hope this helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With