Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MandrilaFreeman's avatar

Laravel hasActiveOneOfMany relation

Obviously this does not exist but I am looking for a way to implement it.

Example, I am playing a game where I have 3 teams but I can only be actively playing for one team at any time and when I switch team I essentially starting from the beginning but I would like to retain the progress if I switch team.

My tables would look something like this:

Users:

active_team_id TeamProgress:

user_id team_id team_level team_xp TeamNames:

id team_name So there would only be 3 teams defined in TeamNames and while any one of these 3 are active (as set in active_team_id in the users table) then I want to be able to directly target it with something like

$user->teamProgress->update() and update the active team directly.

Similarly I would like to do something like

$user->teamProgress->get() and just get the team progress for that users active team while a few others may exist within team progress.

Then if I switch the active_team_id on the user table and do the same calls above I now update / get info for the second team specified in active_team_id

Is there a way to do this with a relation or am I overthinking this and better off doing this by just directly targeting the TeamProgress model using the information I already have as a user?

$teamProgress->where('user_id', $user->id)->where('team_id', $user->active_team_id)->get()

0 likes
1 reply
Funfare's avatar

You can create a relation vor the active team and then use just this relation

public function activeTeam() {
return $this->belongsTo(Team::class, 'active_team_id')
}

Please or to participate in this conversation.