php - Laravel relationship manytomany paginate issue -


i have 3 tables / models

user (has id) articles (has id ) userarticles (has id, article_id , user_id) 

i little confused on how set relationship able articles connected user can set call in controller:

$articles = user::find(auth::user()->id)->articles->paginate(20); 

i figured manytomany relationship playing around code inside user model:

public function articles() {     return $this->belongstomany('app\article', 'user_saved_articles', 'user_id', 'article_id'); } 

now works, long don't call paginate() on controller function i'd use above. here real issue lies now, works with

$articles = user::find(auth::user()->id)->articles; 

but this:

$articles = user::find(auth::user()->id)->articles->paginate(20); 

it comes error:

fatalerrorexception in usercontroller.php line 217: call undefined method illuminate\database\eloquent\collection::paginate() 

i can't figure out why can't paginate on this, can other queries.

if call eloquent relation attribute user::find(auth::user()->id)->articles automatically execute sql, , return collection. error telling you have collection, can't call paginate() on.

if want reference relationship add more statements need call function user::find(auth::user()->id)->articles(). return querybuilder instance can add statements to, and/or paginate.

so should work:

$articles = user::find(auth::user()->id)->articles()->paginate(20); 

Comments