如何使用API​​资源更改json格式?

时间:2018-11-13 11:44:46

标签: php laravel laravel-5.6

我正在尝试将项目status推入数组,然后通过API资源返回,但是API资源返回错误。我正在尝试按照脚本进行操作

$Games = Game::all();
return new GameResource($Games);

它返回如下

{
    "data": [
        {
            "id": 1,
            "name": "similique",
            "type_id": 3,
            "created_at": "2018-10-30 11:23:27",
            "updated_at": "2018-10-30 11:23:27"
        }
    ]
}

我正在尝试实现我想要的json数组

$Games = Game::all();
$DataArray = ['status' => 'success', 'data' =>$Games ];
return new GameResource($DataArray);

但是它返回错误

Call to a member function toBase() on array in fil

我想要的json数组紧随

{
    "status": "success",
    "data": [
        {
            "id": 1,
            "name": "similique",
            "type_id": 3,
            "created_at": "2018-10-30 11:23:27",
            "updated_at": "2018-10-30 11:23:27"
        }
    ]
}

4 个答案:

答案 0 :(得分:1)

您可以尝试以下代码:

$games = Game::get();

return response()->json(new GameResource($games));

答案 1 :(得分:1)

在您的GameResource.php中,更改toArray()方法:

/**
 * Transform the resource into an array.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'data' => $this->collection,
        'status' => 'success', // Here goes the logic which checks for success or failure. However, this depends on what you consider as "success".
   ];
}

答案 2 :(得分:0)

数据是您GameResource的公共财产吗?那么您的代码应该是

return ['status' => 'success', 'data' => (new GameResource($Games))->data ];

答案 3 :(得分:0)

兄弟,我正在使用这种方式。

第1步:我创建了generalOutput Resource.php并进行了如下修改。

class GeneralOutputResource extends JsonResource
{
    private $status;
    private $data;
    public function __construct($status, $data)
    {
        $this->status = $status;
        $this->data = $data;
    }
    public function toArray($request)
    {
       return ['status' => $this->status, 'data' => $this->data];
    }
}

步骤2:  然后我就这样叫课

 $a_user = User::find(1);
 return new GeneralOutputResource(1, $a_user);
  • 每次返回响应时,我都会调用GeneralOutputResponse。