从Laravel数据库创建关联数组

问题描述

目前,我正在使用Flutter构建应用程序,但我的Laravel api控制器未提供适当的多维数组。我想拥有{[0] =>数组,[1] => array等)。如果有人知道解决方法,将不胜感激

public function index()
    {
        $payments = Payment::all();

        return $payments;
    }

它返回此:

[
    {
        "id": 1,"description": "test","price": "9.00","currency": "EUR","status": "open","deleted_at": null,"created_at": "2020-08-10T09:50:52.000000Z","updated_at": "2020-08-10T09:50:52.000000Z"
    },{
        "id": 2,"price": "3.00","currency": "USD","created_at": "2020-08-13T19:06:23.000000Z","updated_at": "2020-08-13T19:06:23.000000Z"
    }
]

我已经尝试了很多,这使我最接近,但是后来我得到了1:{ARRAY}

我尝试过的代码

public function index()
    {
        $data = [];
        $payments = Payment::all();
        $id=1;
        foreach($payments as $payment){
            array_push($data,[$id=>$payment]);
            $id++;
        }
        return $data;
    }

结果:

[
    {
        "1": {
            "id": 1,"updated_at": "2020-08-10T09:50:52.000000Z"
        }
    },{
        "2": {
            "id": 2,"updated_at": "2020-08-13T19:06:23.000000Z"
        }
    }
    
]

我想要:

{
1:{
   "message":"test","price":"9"
   "currency":"EUR"
  },2:{
   "message":"test","price":"9"
   "currency":"EUR"
}
}

解决方法

尝试这个

public function index()
{
    $payments = Payment::get()->toArray();

    return $payments;
}
,

也尝试一下

  public function index(){
    $payments = Payment::all();
    return response()->json([$payments]);
 }