Error when using ->paginate() with Laravel

北慕城南 提交于 2019-12-13 02:35:29

问题


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:


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;
}


来源:https://stackoverflow.com/questions/25027615/error-when-using-paginate-with-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!