-2

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
}
}
Yeo Bryan
  • 331
  • 4
  • 24
  • You have syntax errors ... [activate error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) then [fix your errors](https://stackoverflow.com/questions/18050071/php-parse-syntax-errors-and-how-to-solve-them). – Definitely not Rafal Oct 06 '21 at 10:23

1 Answers1

-1

OK, well, it's a bit of a mess.

Firstly, as Definitely not Rafal says, you have multiple syntax errors (missing brackets, semi-colons, a $ before "foreach", no "as" in your foreach loop) which will explain why nothing is working.

Secondly, you are trying to load $manual_tickets based on a value for 'user_id' but then looping through each $manual_tickets and looking at the user_id to work out what to do, but the user_id for all the $manual_tickets will be the same for each of them, because you're only loading them for one specific user_id. So it's a bit pointless.

Finally, set up the relationships between your User, ManualTicket and TicketFlow models properly and you can just load ManualTickets based on the 'user_id' field (or, which I've not done below, load the User and then access their ManualTickets through them, and it's a lot easier.

This should go some way to getting you on track, though :

$user_id = $this->encrypt_decrypt('decrypt', $request->userid);
$manual_tickets = ManualTicket::where("user_id", $user_id)->get();
foreach($manual_tickets as $mt){
    if($user_id == 1){
        $mt->ticket_flow->price = "50";
    } elseif($user_id == 2){
        $mt->ticket_flow->price = "100";
    }
}
Giles Bennett
  • 1,509
  • 1
  • 12
  • 15