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

bwrigley's avatar

How to access an accessor on a pivot model via relationship

In my forum project a User can have many Posts and a Post can have many Tags (and a Tag can also belong to many Posts).

Also a User can create a Follow of another User or of a Tag. So the Follow has a BelongsTo relationship with it's owner; a User and a MorphTo relationship to either a User or a Tag that it's following; followable()

My Follow model also has a couple of accessors e.g.:

    protected function unseen(): Attribute
    {
        return Attribute::make(
            get: function() {
                return Cache::rememberForever('follow_unseen_' . $this->id, function () {
                    return $this->followable->posts->where('postable_type',Post::class)->where('created_at','>',$this->seen_at)->count();
                });
            }
        );
    }

This gives me a count of new related Posts since the last time this Follow was 'seen' and I can pass it on to my Vue front end.

What I'm not sure is how to to access this unseen attribute via the relationship. Here is the simple test I am trying to write:

        $follower = User::factory()->create();
        $tag = Tag::factory()->create();
        $follower->tagFollows()->attach($tag);

        $this->assertEquals(0, $follower->tagFollows->first()->unseen);

        $post = Post::factory()->create();
        $post->tags()->attach($tag);

        $this->assertEquals(1, $follower->tagFollows->first()->unseen);

I can see how to access data from the pivot table but not an accessor. Thanks for any help!

0 likes
1 reply
bwrigley's avatar
bwrigley
OP
Best Answer
Level 5

I think I solved it now:

So I needed to make my Follow model extend MorphPivot and the add the using() method to my relationships.

So it my Tag model I now have:

public function followers(): MorphToMany

    {
        return $this->morphToMany(User::class,'followable','follows')->using(Follow::class);

    }

and my User model:

    public function tagFollows(): MorphToMany

    {
        return $this->morphedByMany(Tag::class,'followable','follows')->using(Follow::class);

    }

Which means that I can do:

        $follower = User::factory()->create();
        $tag = Tag::factory()->create();
        $follower->tagFollows()->attach($tag);
		$follow = $follower->tagFollows->first()->pivot;

        $this->assertEquals(0, $follow->unseen);

        $post = Post::factory()->create();
        $post->tags()->attach($tag);
		$follow->refresh();

        $this->assertEquals(1, $follow->unseen);

Please or to participate in this conversation.