1

I am building a RESTful API with Laravel 5.1 - When a post request is made, I validate the input, if the input is not valid, I throw an exception.

Current Response Sample:

{
    "message": "{\"email\":[\"The email field is required.\"]}",
    "status_code": 400
}

How to make my response look like this:

{
    "message": {
        "email": "The email field is required."
     },
    "status_code": 400
}

Here's how I throw the exception:

$validator = Validator::make($this->request->all(), $this->rules());

if ($validator->fails()) {
    throw new ValidationFailedException($validator->errors());
}
Mahmoud Zalt
  • 30,478
  • 7
  • 87
  • 83

4 Answers4

3

I think the best way to validate the form in laravel is using Form Request Validation .You can overwrite the response method in App\Http\Request.php class.
Request.php

namespace App\Http\Requests;
Illuminate\Foundation\Http\FormRequest;

abstract class Request extends FormRequest
{
    public function response(array $errors)
    {
        return $this->respond([
                'status_code'   => 400 ,                                 
                'message'          => array_map(function($errors){         
                        foreach($errors as $key=>$value){
                            return $value;                           
                        }                       
                    },$errors)
            ]);
    }


    /**
     * Return the response 
     */
    public function respond($data , $headers=[] ){
        return \Response::json($data);
    }
}
Kiran Subedi
  • 2,244
  • 3
  • 17
  • 34
  • Looks like in 5.5 the method to override instead is `failedValidation`: https://stackoverflow.com/a/46331799/1110820 – Charles Wood Jan 24 '20 at 18:01
2

You can try this:

$messages = [
    'email.required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);
vard
  • 4,057
  • 2
  • 26
  • 46
dhamo dharan
  • 138
  • 2
  • 11
0

Here is a class I use:

<?php

namespace App;

class Hack
{
    public static function provokeValidationException($field_messages){
        $rules = [];
        $messages = [];
        foreach($field_messages as $field=>$message){
            $rules[$field] = 'required';
            $messages[$field. '.required'] = $message;
        }

        $validator = \Validator::make([], $rules, $messages);
        if ($validator->fails()) {
            throw new \Illuminate\Validation\ValidationException($validator);
        }
    }
}

Then any time I need to show custom errors, I do:

\App\Hack::provokeValidationException(array(
    'fieldname'=>'message to display',
    'fieldname2'=>'message2 to display',
));
Ibrahim Lawal
  • 1,168
  • 16
  • 31
0

I had this same issue and I resolved it by decoding my the $validator->errors() response

return (400, json_decode($exception->getMessage()));
Emmac
  • 2,928
  • 2
  • 15
  • 22