hillcow's avatar

Paginate blog example from "Laravel 5.4 from Scratch series"

Hi there,

I followed the Laravel 5.4 from Scratch series and am currently trying to implement pagination into the blog example.

It's easy to get pagination for the homepage:

Post::latest()->filter(request(['month', 'year']))->simplePaginate(5);

Problem: paginate() or simplePaginate() cannot be called like this:

public function index(Tag $tag){
$posts = $tag->posts->paginate(5);
return view('posts.index', compact('posts'));
}

So when I visit /posts/tags/{tag}, it tells me method paginate() doesn't exist. How am I supposed to paginate the results in that case, so that I can still hand over the Eloquent model of Post (which I need to display all the details)?

Thank you very much!

0 likes
2 replies
cviv's avatar
cviv
Best Answer
Level 3

have you tried

$posts = $tag->posts()->paginate(5);

better try our query with tinker

1 like
fraserk's avatar

You'll need to get the Post with tages first

something like

Post::whereHas('Tag'=>function($query) use($tag){
    $query->where('tag', $tag;
})->paginate(10);

Please or to participate in this conversation.