phparrayslaravelapiassociate

Creating an Associate array from Laravel db


At the moment I am building an app with flutter but my Laravel api controller doesn't give the appropiate multidimensional array back. I would like to have { [0]=> array,[1]=>array, etc}. If anyone knows the fix for this it would be highly appreciated

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

        return $payments;
    }

And it returns this:

[
    {
        "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,
        "description": "test",
        "price": "3.00",
        "currency": "USD",
        "status": "open",
        "deleted_at": null,
        "created_at": "2020-08-13T19:06:23.000000Z",
        "updated_at": "2020-08-13T19:06:23.000000Z"
    }
]

I have tried a lot, this has got me the closest but then i got 1:{ARRAY}

code i tried:

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

Outcome:

[
    {
        "1": {
            "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"
        }
    },
    {
        "2": {
            "id": 2,
            "description": "test",
            "price": "3.00",
            "currency": "USD",
            "status": "open",
            "deleted_at": null,
            "created_at": "2020-08-13T19:06:23.000000Z",
            "updated_at": "2020-08-13T19:06:23.000000Z"
        }
    }
    
]

I would like to have:

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

Solution

  • Try Also this

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