Reputation: 2370
I'm trying to create an array with Laravel but customise some of the values.
For example, if I was to return $user->rounds
this would return
"data": [
{
"id": 3,
"name": "sample name"
},
{
"id": 4,
"name": "sample name 2"
}
]
I want to customise the return to something like
"data": [
{
"id": 3,
"name": "sample name",
"extra": "Extra Detail"
},
{
"id": 4,
"name": "sample name 2",
"extra": "Extra Detail"
}
]
I'm trying to do it, by the following code:
$data = array();
foreach ($user->rounds as $r) {
$data = [
'id' => $r->id,
'name' => $r->name,
'extra' => 'Test Extra'
];
}
return $data;
But it returns only one round while it should be returning 3.
Upvotes: 0
Views: 70
Reputation: 2736
Try to do like this
$data = array();
$i=0;
foreach($user->rounds as $r){
$data[$i] = [
'id' => $r->id,
'name' => $r->name,
'extra' => 'Test Extra'
];
$i++;
}
return $data;
Upvotes: 0
Reputation: 163748
You need to add array to $data
array with each iteration:
$data[] = [
'id' => $r->id,
'name' => $r->name,
'extra' => 'Test Extra'
];
Also, you could use array_push()
function for that.
Upvotes: 1