mardi 6 juin 2017

Laravel json response not showing custom object data

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)?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire