php - Creating an Associate array from Laravel db
Get the solution ↓↓↓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"
}
}
Answer
Solution:
Try Also this
public function index(){
$payments = Payment::all();
return response()->json([$payments]);
}
Answer
Solution:
Try this one
public function index()
{
$payments = Payment::get()->toArray();
return $payments;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: git was not found in your path, skipping source download
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.