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

orest's avatar
Level 13

ignore data from ignored users

I have the following tables

users
- id
threads
- id
replies
- id
- thread_id
ignored
- id
- user_id
- ignored_id
  • When a user visits a list of thread, I want the threads by the ignored users to not be fetched
  • When a user visits a thread, I want the replies by the ignored users to not be fetched

I'm wondering if is a good idea to include the query that filters the data from ignored users inside the relationships

class Thread
{
      public function replies()
      {
                  if(!auth()->check())
                  {
                            return $this->hasMany(Reply::class);
                  }

                  $ignoredUserIds = auth()->user()->ignoredUsers()->pluck('id');
                  return $this->hasMany(Reply::class)->whereNotIn('replies.user_id', $ignoredUserIds);
       }

}

or whether I should add that query outside of the relationship.

class ReplyController
{
        public function index(Thread $thread)
        {
                  if(!auth()->check())
                  {
                            return $this->replies()->get();
                  }

                  $ignoredUserIds = auth()->user()->ignoredUsers()->pluck('id');
                  return $this->replies()->whereNotIn('replies.user_id', $ignoredUserIds);
         }
}

To me, it makes sense to add it inside the relationship since that would be the "default" query But I don't know if that's too much code for a relationship

Or is there a better approach ?

0 likes
1 reply
orest's avatar
Level 13

or maybe it would be even better to add a global scope


class Reply
{
/**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope('notIgnored', function ($builder) {
            return $builder->whereNotIgnored();
        });
    }

 public function scopeWhereNotIgnored($query)
    {
        if (!auth()->check()) {
            return $query;
        }

        $ignoredUserIds = auth()->user()->ignoredUsers()->pluck('users.id');

        return $query->whereNotIn("{$this->getTable()}.user_id", $ignoredUserIds);

    }
}

Please or to participate in this conversation.