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.
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 :)
You are not converting validation errors to array.Please use the below function and pass validation errors as parameter.
public function validationErrorsToString($errArray) {
$valArr = array();
foreach ($errArray->toArray() as $key => $value) {
$errStr = $key.' '.$value[0];
array_push($valArr, $errStr);
}
if(!empty($valArr)){
$errStrFinal = implode(',', $valArr);
}
return $errStrFinal;
}
//Function call.
$result = $this->validationErrorsToString($validator->errors());
来源:https://stackoverflow.com/questions/44517760/laravel-validation-error-messages-to-string