Laravel Validation Error customise format of the R

2019-03-04 03:15发布

问题:

I am working with L5 Form Requests and don't I just love Taylor! Well, I am doing some AJAX requests and I still want to retain my form requests. The problem is that in the case of a validation error the Validator just returns a 422 error response and flashes the errors, but my AJAX frontend expects a very specific format of response from server whether validation is successful or not.

I want to format the response on Validation errors to something like this

return json_encode(['Result'=>'ERROR','Message'=>'//i get the errors..no problem//']);

My problem is how to format the response for the form requests, especially when this is not global but done on specific form requests.

I have googled and yet not seen very helpful info. Tried this method too after digging into the Validator class.

// added this function to my Form Request (after rules())
    public function failedValidation(Validator $validator)
{
    return ['Result'=>'Error'];
}

Still no success.

回答1:

Currently accepted answer no longer works so i am giving an updated answer.

In the revelent FormRequest use failedValidation function to throw a custom exception

  // use Illuminate\Contracts\Validation\Validator; 
  // use App\Exceptions\MyValidationException; at top

  protected function failedValidation(Validator $validator)
  {
    throw new MyValidationException($validator);
  }

Create your custom exception in app/Exceptions

    <?php

    namespace App\Exceptions;

    use Exception;
    use Illuminate\Contracts\Validation\Validator;

    class MyValidationException extends Exception
    {
      protected $validator;

      protected $code = 422;

      public function __construct(Validator $validator)
      {
        $this->validator = $validator;
      }

      public function render()
      {
        // return a json with desired format
        return response()->json([
            "error" => "form validation error",
            "message" => $this->validator->errors()->first()
        ], $this->code);
      }
    }

This is the only way I found. If there is a better approach please leave a comment.

This works in laraval5.5, I don't think this will work in laravel5.4 but i am not sure.



回答2:

Found the answer here: Laravel 5 custom validation redirection
All you need to do is to add a response() method in your form request and it will override the default response. In your response() you can redirect in whatever fashion you want.

public function response(array $errors)
{
    // Optionally, send a custom response on authorize failure 
    // (default is to just redirect to initial page with errors)
    // 
    // Can return a response, a view, a redirect, or whatever els
    return response()->json(['Result'=>'ERROR','Message'=>implode('<br/>',array_flatten($errors))]); // i wanted the Message to be a string
}

UPDATE on L5.5+
This error and the accepted solution was for L5.4. For L5.5, use Ragas' answer above (failedValidation() approach)