2

So I have this Topic controller on my forum. The Topic has many Posts and the Post belongs to the Topic.

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

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

To get the informations about a Topic and all of the posts related to it, I do:

$query = Topic::where('id', $id)->with('posts');

But every time I try to add :

$query = $query->paginate(15)

and I use $topic->title, I get :

Undefined property: Illuminate\Pagination\Paginator::$title

Any idea? Thank you.

EDIT : Oh and if I use ->get() instead of ->paginate() I don't have errors.

1 Answer 1

3

The paginate(15) call returns a Paginator object, holding many Topic items. If you want to get the title field of one of these items, you need to get one of them first. You can do this for example via:

$query->first()->title;

More likely, you will loop through the results and use them like that:

foreach($query as $key => $value)
{
    // do something here, $value contains a Topic object.
    $name = $value->name;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I didn't get that :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.