Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 565
Nithin John Avatar asked Jun 13 '17 09:06

Nithin John


People also ask

How do I show laravel validation errors in blade?

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.

How do you validate exact words in laravel?

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.

What is the method used for specifying custom message for validation errors in form request?

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.


2 Answers

You should do like this :

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

P.S. Assuming

$validator = Validator::make($dataToBeChecked,$validationArray,$messageArray)
like image 189
stackMonk Avatar answered Sep 30 '22 15:09

stackMonk


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

like image 22
alistaircol Avatar answered Sep 30 '22 13:09

alistaircol