My collection:
($usersWithCommission) Illuminate\Support\Collection {#2625
#items: array:2 [
0 => array:3 [
"userId" => 1
"name" => "Sim Aufderhar"
"net_commission" => null
]
1 => array:3 [
"userId" => 2
"name" => "Carolyn Lang III"
"net_commission" => null
]
]
}
I would like modify the net_commission property, but I can not:
foreach ($soldProperties as $property) {
if (!$property->buyer_user_id && !$property->seller_transferring_user_id) {
$usersWithCommission->where('userId', $property->user_id)->first()['net_commission'] += $property->net_commission_of_sold;
}
}
How I can? Thanks your answers.
Collections provide a method map which allows you to iterate your collection and add/modify fields.
function modify_net_commision($var) {
return YOUR_LOGIC_HERE;
}
$collection = [
[ "userId" => 1, "name" => "Sim Aufderhar", "net_commission" => null ],
[ "userId" => 2, "name" => "Carolyn Lang III", "net_commission" => null ],
];
$external_var = 'I will be used on modify_net_commision function';
$new_collection = collect($collection)->map(function ($arr) use ($external_var) {
$arr['net_commission'] = modify_net_commision($external_var);
return $arr;
})
If you want to remove some fields from your collection, use reject method.
Doc: https://laravel.com/docs/5.8/collections
Hope it helps you.
Have a great day.
public function test()
{
$collection = [
[ "userId" => 1, "name" => "Sim Aufderhar", "net_commission" => null ],
[ "userId" => 2, "name" => "Carolyn Lang III", "net_commission" => null ],
];
$data= collect($collection)->map(function($collection, $key) {
$collect = (object)$collection;
return [
'userId' => $collect->userId,
'name' => $collect->name,
'net_commission' => $this->modify_commision($key)
];
});
dd($data);
}
public function modify_commision($key) {
$property = [
['userId' => 1 ,'net_commission_of_sold' => 30],
['user_id' => 2,'net_commission_of_sold' => 40]
];
return $property[$key]['net_commission_of_sold'];
}
***Hope it helps you***
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With