Nithin John Nithin John -4 years ago 91
PHP Question

Laravel validation Error messages to string

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.

Answer Source
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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download