79293957

Date: 2024-12-19 10:39:41
Score: 2
Natty:
Report link

@Hefer thank alot, i was able to make it work by modifying the allCards method in controller like this

   private function allCards($userid)
   {
       $user = User::find($userid);
   
       // Fetch UserHashCards with their exchanges and associated usernames
       $userHashCards = UserHashCard::query()
           ->where('user_id', $user->id)
           ->with([
               'hashCard', // Existing relationship
               'initiatedExchanges' => function ($query) {
                   $query->with(['user:id,username']); // Eager load only the `id` and `username` fields from `users`
               },
               'joinedExchanges'  => function ($query) {
                   $query->with(['user:id,username']); // Eager load only the `id` and `username` fields from `users`
               }
           ])
           ->orderByRaw("
               CASE 
                   WHEN status = 'initiated' THEN 1
                   WHEN status = 'joined' THEN 2
                   ELSE 3
               END
           ")
           ->get();
   
           // Dynamically map exchanges based on card status and remove extra fields
           $userHashCards->transform(function ($card) {
               $card->exchanges = match ($card->status) {
                   'initiated' => $card->initiatedExchanges,
                   'joined' => $card->joinedExchanges,
                   default => collect(),
               };
       
               // Remove initiated_exchanges and joined_exchanges fields
               unset($card->initiatedExchanges, $card->joinedExchanges);
       
               return $card;
           });
       
     return $userHashCards;
   }
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Hefer
  • Self-answer (0.5):
  • Looks like a comment (1):
  • Low reputation (1):
Posted by: odion_cloud