@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;
}