Skip to content

Commit

Permalink
fix: tag state loaded for wrong user (#4009)
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaucau authored Sep 20, 2024
1 parent aafc615 commit e1a77fd
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions extensions/tags/src/Tag.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
* @property int $last_posted_user_id
* @property string $icon
*
* @property TagState $state
* @property TagState|null $state
* @property Tag|null $parent
* @property-read Collection<int, Tag> $children
* @property-read Collection<int, Discussion> $discussions
Expand Down Expand Up @@ -166,7 +166,16 @@ public function state(): HasOne
*/
public function stateFor(User $user): TagState
{
$state = $this->state()->where('user_id', $user->id)->first();
// Use the loaded state if the relation is loaded, and either:
// 1. The state is null, or
// 2. The state belongs to the given user.
// This ensures that if a non-null state is loaded, it belongs to the correct user.
// If these conditions are not met, we query the database for the user's state.
if ($this->relationLoaded('state') && (! $this->state || $this->state->user_id === $user->id)) {
$state = $this->state;
} else {
$state = $this->state()->where('user_id', $user->id)->first();
}

if (! $state) {
$state = new TagState;
Expand Down

0 comments on commit e1a77fd

Please sign in to comment.