简体   繁体   中英

Return validation error message as JSON - Laravel 6

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.

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]);
                    }

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');
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM