I am trying to iterate through the data returned by the eloquent query and add properties to the object depending on the user id.
However, when changing the values in the nested relationship (ticket_flow) it causes the price property in the two different manual ticket's ticket_flow to change to the value that was set later.
Which in this case it causes both the price to be set to $100. Can someone help me out
$manual_tickets = ManualTicket::where("user_id", "=", $this->encrypt_decrypt('decrypt', $request->userid)->orderBy('priority')->with('ticket_flow_order.ticket_field_template')
$foreach($manual_tickets $mt){
if($mt->user_id == 1){
$mt->ticket_flow->price = $50
}
elseif($mt->user_id == 2){
$mt->ticket_flow->price = $100
}
}
My Answer:
To achieve the desired result, you need to loop through the `ticket_flow_order` relationship instead of directly accessing the `ticket_flow` property. Here's how you can modify your code:
php
$manual_tickets = ManualTicket::where("user_id", "=", $this->encrypt_decrypt('decrypt', $request->userid)->orderBy('priority')->with('ticket_flow_order.ticket_field_template')->get();
foreach($manual_tickets as $mt){
foreach($mt->ticket_flow_order as $tfo){
if($mt->user_id == 1){
$tfo->ticket_flow->price = 50;
} elseif($mt->user_id == 2){
$tfo->ticket_flow->price = 100;
}
}
}
By looping through the `ticket_flow_order` relationship, you can access each `ticket_flow` object individually and set the price based on the user id. This way, the price of each `ticket_flow` object will be set correctly without affecting other objects.
Rate this post
4 of 5 based on 7340 votesComments