Reputation: 315
I would like to add new element to each existing element in Laravel object collection in Laravel. My object is something like this,
object(Illuminate\Support\Collection)#178 (1) {
["items":protected]=>
array(10) {
[0]=>
object(stdClass)#175 (4) {
["fname"]=>
string(6) "xxx"
["lname"]=>
string(5) "xxx"
["data2"]=>
string(3) "xxx"
["callid"]=>
string(17) "xxx"
}
[1]=>
object(stdClass)#179 (4) {
["fname"]=>
string(6) "xxx"
["lname"]=>
string(5) "xxx"
["data2"]=>
string(2) "62"
["callid"]=>
string(17) "xxx"
}
}
So I need to add something like ["phonenumber"]=>string(17) "xxx" to each block. Then object looks like this,
object(Illuminate\Support\Collection)#178 (1) {
["items":protected]=>
array(10) {
[0]=>
object(stdClass)#175 (4) {
["fname"]=>
string(6) "xxx"
["lname"]=>
string(5) "xxx"
["data2"]=>
string(3) "xxx"
["callid"]=>
string(17) "xxx"
["phonenumber"]=>
string(17) "xxx"
}
[1]=>
object(stdClass)#179 (4) {
["fname"]=>
string(6) "xxx"
["lname"]=>
string(5) "xxx"
["data2"]=>
string(2) "62"
["callid"]=>
string(17) "xxx"
["phonenumber"]=>
string(17) "xxx"
}
}
My code is something like this
$resultsInCalls....
foreach ($resultsInCalls as $key=>$value) {
$resultsUserNumber = DB::table('qlog')
->select('data2')
->where('event', '=', 'ENTERQUEUE')
->where('callid', '=', $value->callid)
->get();
$resultsInCalls->push('phoneNumber', $resultsUserNumber['0']->data2);
}
But above code adds somthing like this instead expected result,
[5]=>
string(11) "phoneNumber"
[6]=>
string(11) "phoneNumber"
[7]=>
string(11) "phoneNumber"
[8]=>
string(11) "phoneNumber"
[9]=>
string(11) "phoneNumber"
How do I get expected result. Please help.
Upvotes: 0
Views: 1895
Reputation: 32354
Loop the collection using each
$resultsInCalls = $resultsInCalls->each(function ($item, $key) {
$resultsUserNumber = DB::table('qlog')
->select('data2')
->where('event', '=', 'ENTERQUEUE')
->where('callid', '=', $item->callid)
->get();
$item->phoneNumber = $resultsUserNumber['0']->data2;
});
A better way will be using a relationship or a join
Upvotes: 3