Return validation error message as JSON - Laravel 6

懵懂的女人 提交于 2021-02-10 16:51:14

问题


I want to return a failed validation attempt message in JSON. I used something like this before, which was working on Laravel 5, I believe...

if ($validator->fails()) {    
    return response()->json($validator->messages(), 200);
}

However, for our new project we are using Laravel 6 and the above just returns a blank page.

In Laravel 6 the following returns the error message successfully, albeit not in JSON...

if ($validator->fails()) {  
    $msg = $validator->messages();
    dd($msg);
}

There must be a change in the way response() works in Laravel 6.

Any ideas how I get the Validation messages to get returned in JSON in Laravel 6? Thanks.


回答1:


This should works

 $validator = Validator::make($request->all(), [
                'email' => 'required|email',
                'password' => 'required',
            ]);

     if ($validator->fails()) {
                        $messages = $validator->errors()->all();
                        $msg = $messages[0];
                        return response()->json(['success_code' => 401, 'response_code' => 0, 'response_message' => $msg]);
                    }



回答2:


Here,

if($validatedData->fails()){
   return response()->json([
      'status'   => 'error',
      'message'  => $validatedData->getMessageBag()
   ],400);
}

You can grab these errors in JSON, This is sample code

 $.ajax({
    url: "{{ route('your_route_name') }}",
    method: 'post',
    cache: false,
    contentType: false,
    processData: false,
    data: formData,
    success: function(response){
        //....YOUR SUCCESS CODE HERE
    },
    error: function(response){
        // HERE YOU CAN GET ALL THE ERRORS IN JSON
        var data = JSON.parse(response.responseText);
        if(data.message){
            if(data.message.f_name){
                $('input[name=f_name]')
                .parents('.form-group')
                .find('.help-block')
                .html(data.message.f_name)
                .css('display','block');
            }else{
                $('input[name=f_name]')
                .parents('.form-group')
                .find('.help-block')
                .html('')
                .css('display','none');
            }
        }else{
            $('.help-block').html('').css('display','none');
        }
    }
});


来源:https://stackoverflow.com/questions/58061391/return-validation-error-message-as-json-laravel-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!