Jake2018
Jake2018

Reputation: 93

PHP Laravel Pagination: Method links does not exist

Hi I'm trying to setup pagination for a simple comments page.

I'm getting the error Method links does not exist.

Is it due to the comments being referenced from it's relationship to the post class?

Can't work out what to do here...

CommentController.php

public function show($id)
{   
    $comments = Comment::find($id)->paginate(5);
    return view('posts.show')->with('comments', $comments);
}

show.blade.php

@foreach ($post->comments as $comment)
    <li>
        User Name: {{ $comment->user_name }} <br>
        Comment: {{ $comment->comment }} <br>
    </li><br>
@endforeach

{{ $post->comments->links() }}

Upvotes: 1

Views: 272

Answers (3)

Rp9
Rp9

Reputation: 1963

create the pagination links using the render method:

@foreach ($post->comments as $comment)
    <li>
        User Name: {{$comment->user_name}} <br>
        Comment: {{$comment->comment}} <br>
    </li><br>
    @endforeach
    {!! $comments->render() !!}

Upvotes: 0

Vinesh Goyal
Vinesh Goyal

Reputation: 637

find() function find only one record and paginate workes with query builder or an Eloquent query, so you can use

$comments= Comment::where('post_id', $id)->paginate(5);

and replace $post->comments to $comments, it should be

@foreach ($comments as $comment)
    <li>
        User Name: {{$comment->user_name}} <br>
        Comment: {{$comment->comment}} <br>
    </li><br>
@endforeach
{{$comments->links()}}

Upvotes: 1

user8034901
user8034901

Reputation:

In your controller method you are paginating $comments but use $post->comments in your view. Replace your code with:

@foreach ($comments as $comment)
    <li>
        User Name: {{$comment->user_name}} <br>
        Comment: {{$comment->comment}} <br>
    </li><br>
@endforeach
{{$comments->links()}}

Upvotes: 0

Related Questions