我有以下类:Laravel JSON响应未示出的自定义对象数据
<?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;
}
}
然后,控制器我有作为响应于:
$data['message'] = 'hello';
$data['error'] = new ErrorResponse($code, 'Something is bad');
return response()->json($data, $code);
在我得到以下结果的应答:
{
"error": {},
"message": "hello"
}
但我期待
{
"error": {
"code": 422,
"message": "Something is bad"
},
"message": "hello"
}
有关如何使Laravel响应嵌套对象(ErrorResponse)内容的任何想法?
您需要实现'JsonSerializable'接口或公开$ error。 – jfadich