1
votes

I have a Model Topic and Post.

Each Topic has many Post.

My Topic model extends Eloquent with a one-to-many relationship for Post.

class Topic extends Eloquent
{

    public function posts()
    {
        return $this->hasMany('Post');
    }

}

My Post model also extends Eloquent.

class Post extends Eloquent
{

    public function topic()
    {
        return $this->belongsTo('Post');
    }

}

In my TopicController, I would like to paginate my posts through the relationship. I expended something like this would work:

$topic->posts->paginate(20);

However, it is a Collection object. As such, I get the following error message.

Call to undefined method Illuminate\Database\Eloquent\Collection::paginate()

How do I correctly paginate a one-to-many relationship?

1

1 Answers

2
votes

The problem here is that $topic->posts is different from $topic->posts(). While the former is an Illuminate\Database\Eloquent\Collection object. The latter is an Illuminate\Database\Eloquent\Relations\HasMany object.

Therefore, the following would work.

$topic->posts()->paginate(20);