Laravel Paginate displaying results unexpectedly

216 views Asked by At

Controller function for showing all the posts on home page (works fine, I can click through and see all posts listed as expected):

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

class PostsController extends Controller
{

    public function showPosts()
    {
        $posts = Post::paginate(5);
        return view('index', ['posts' => $posts]);
    }

Controller function for showing all posts on other pages:

use App\Page;
use App\Post;
use Illuminate\Http\Request;

class PagesController extends Controller
{
    public function show($slug)
    {
        $posts = Post::paginate(16);
        $page = Page::findBySlug($slug);
        return view('page', ['page' => $page, 'posts' => $posts]);
    }

To display on the index I have inside index.blade:

    @foreach ($posts as $post)
    @include('partials.post', ['post' => $post])
    @endforeach

To display on the other pages I have inside pages.blade:

    {{ $posts->links() }}

    @foreach ($posts as $post)

    <?php
    {
        if ($post->category_id == $page->id){?>
            @include('partials.post', ['post' => $post])
        <?php  }
    }?>
    @endforeach

The home page works fine. The other pages work to a degree. They shows the correct posts on the correct pages. The issue is with the pagination.

Using the 16th post as an example, if I say $posts = Post::paginate(16); then the post display on the page and there is no pagination buttons shown as the total number of posts is 16. If I say $posts = Post::paginate(2); then the 16th post appears on pagination page 8, even when it is the only post for that page.

1

There are 1 answers

2
shukshin.ivan On BEST ANSWER

I think you understand paginator wrong. You should paginate filtered results. Not filter paginated ones.

PagesController:

$page = Page::findBySlug($slug);
$posts = Post::where('category_id', $page->id)->paginate(16);