简体   繁体   中英

Laravel custom response json

I have a useful response result that I have developed. But it doesn't return the result exactly as I want, so I can't get the "errorMessage" part.

Following my code : ResponseResult.php

namespace App\Helpers;

class ResponseResult
{
    public static function generate(bool $success = true, $message = null, int $errorCode = 200) : object
    {
        if ($success) {
            return response()->json(['success' => $success, 'message' => $message], $errorCode);
        } else {
            return response()->json(['success' => $success, 'errorMessage' => $message, 'errorCode' => $errorCode],$errorCode);
        }
    }
}

ExampleController

$validate = Validator::make($request->all(), [
            'name' => 'required',
            'lastname' => 'required',
        ]);

 if ($validate->fails()) {
     return ResponseResult::generate(false,$validate->messages(),ResponseCodes::HTTP_BAD_REQUEST);
 }

network output:

{success: false, errorMessage: {name: ["Name field is required."], lastname: ["lastname field is required."]},…}
errorCode: 404
errorMessage: {name: ["Name field is required."], lastname: ["lastname field is required."]}
success: false

I can't print any error when I try to get it as ErrorMessage. Can anyone help with this?

result.errorMessage.forEach(function (data) {
  $('#ajaxFails ul').append('<li>' + data + '</li>');
});

Thank you advance.

If you will console.log(result) you will most likely see that you return data is embed in to the data property. So the right way to display the error message will be:

result.data.errorMessage.forEach(function (data) {
  $('#ajaxFails ul').append('<li>' + data + '</li>');
});

But again... it all depends how you build your data response.

i am returning my validation error like this:

$validate = Validator::make($request->all(), [
            'name' => 'required',
            'lastname' => 'required',
        ]);

 if ($validate->fails()) {
     $error = $validator->errors();
     return response()->json([
        'responseCode' => app('Illuminate\Http\Response')->status(),
        'error' => $error,
        'success' => false,
        'message'=>'',
    ]);
 }

Hope this will help you😐😐😐

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