2

I have the following class:

<?php
namespace App\Libraries;

use Illuminate\Contracts\Support\Arrayable;

class ErrorResponse implements Arrayable {

    private $error;

    function __construct($code, $message) {
        $this->error = array('code' => $code, 'message' => $message);
    }

    function toArray() {
        return $this->error;
    }

}

Then on the controller I have as a response:

$data['message'] = 'hello';
$data['error'] = new ErrorResponse($code, 'Something is bad');
return response()->json($data, $code);

On the response I get the following result:

{
  "error": {},
  "message": "hello"
}

But I was expecting

{
  "error": {
       "code": 422,
       "message": "Something is bad"
  },
  "message": "hello"
}

Any idea on how to make Laravel responds the contents of the nested object (ErrorResponse)?

1
  • You either need to implement the JsonSerializable interface or make $error public. Commented Jun 6, 2017 at 18:10

1 Answer 1

1

Since you give a pure array to json(), Laravel just passes it straight to json_encode. You will either need to:

  1. give the json() call an Arrayable or JsonSerializable object to have Laravel recursively expand the value,
  2. make the $error a public so json_decode can use it, or
  3. do it yourself, given how simple your example is:

    $data['error'] = (new ErrorResponse($code, 'Something is bad'))->toArray();

Sign up to request clarification or add additional context in comments.

1 Comment

Added the interface JsonSerializable and implemented as function jsonSerialize() { return $this->error; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.