Search code examples
phplaravellaravel-request

Laravel form request JSON response: Chinese Language not converted to UTF


I am not sure how I achieve this. My web app is in English and Chinese. I.t's working fine in English, but when it comes to Chinese, the mess starts.

Right now, I am using Laravel default auth, and it's working fine. The issue is when I select the Chinese language the JSON response from the request class is not converted into UTF, and the response looks something like this:

{"message":"The given data was invalid.","errors":{"first_name":["\u540d\u5b57\u4e3a\u5fc5\u586b\u9879"],"last_name":["\u5fc5\u987b\u586b\u5199\u59d3\u6c0f"],"email":["\u7535\u5b50\u90ae\u4ef6\u4e3a\u5fc5\u586b\u9879"],"password":[""],"terms_conditions":[""]}}

I want to convert this response into a UTF string. I know I can do that using json_encode.

json_encode($data, JSON_UNESCAPED_UNICODE); 

The Laravel request class generates the response, but I am not sure how to make it work. The default function resides in the Laravel framework folder, and I don't want to edit that part. If you have ever come to this situation, please share how you have resolved this.

NOTE My request is a registration form, but it's not a regular HTTP request, but I am submitting the form through the Ajax call.


Solution

  • After searching and googling for 5 hours I came to this solution, actually you can return the response from the FormRequest class by over writing this function:

    protected function failedValidation(Validator $validator) {
       $data = ['error' => json_encode($validator,JSON_UNESCAPED_UNICODE)];
       throw new HttpResponseException(response($data,422));
    }
    

    Make sure that you also import:

    use Illuminate\Http\Exceptions\HttpResponseException;
    

    At the top of your class.