Home > Enterprise >  Laravel custom response json
Laravel custom response json

Time:07-09

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.

CodePudding user response:

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.

CodePudding user 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

  • Related