webfuelcode's avatar

How to add pagination in user's posts

@forelse ($user->posts as $post)
                    <div class="col-md-6 col-lg-4">
                        <div class="card mb-4">
                            @if (!empty($post->img1))
                                <img src="/uploads/post_img/{{ $post->img1 }}" class="card-img-top">
                            @endif
                            <div class="card-body">
                                <a href="{{ route('post.show', $post->slug) }}">{{ $post->title }}</a>
                            </div>
                        </div>
                    </div>
                @empty
                    <div class="card bg-secondary w-100 my-4">
                        <div class="card-body text-center text-light">
                            No posts records from {{ $user->name }}!
                        </div>
                    </div>
                @endforelse

Not sure about the controller

public function show($id)
    {
        $user = User::find($id);
        $posts = Post::paginate(6);
        return view('users.show', compact('user', 'posts'))->with('i', (request()->input('page', 1) - 1) * 6);
    }
0 likes
5 replies
munazzil's avatar

In your view use as like below at the end of forelse condition,

   <div>
{!! $posts->links() !!}
</div>

and in the controller use as like below,

    $user = User::find($id);
    $posts = Post::paginate(6);
    return view('users.show', compact('user', 'posts'));
Tray2's avatar

You just do

{{ $post->links() }}
webfuelcode's avatar

I am using @forelse ($user->posts as $post) so do not know how to call the paginate.

Also {{$post->links()}} does not work.

Tray2's avatar

My bad it should be posts not post and you put it outside your loop.

@endforelse

{{ $posts->links() }}

Please or to participate in this conversation.