Laravel validation Error messages to string

2020-06-19 04:17发布

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.

3条回答
你好瞎i
2楼-- · 2020-06-19 04:30

You should do like this :

$errorString = implode(",",$validator->messages()->all());

P.S. Assuming

$validator = Validator::make($dataToBeChecked,$validationArray,$messageArray)
查看更多
家丑人穷心不美
3楼-- · 2020-06-19 04:30

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 :)

查看更多
劫难
4楼-- · 2020-06-19 04:37
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());
查看更多
登录 后发表回答