How to use paginate() on relationship and add fields to model object in Laravel 7?

  collections, dictionary, laravel, paginate, relationship
public function show($id)
{
    $post = Post::find($id);
    $comments = $post->comments()->orderBy('created_at', 'desc')->get()->transform(function ($item, $key) {
        $item->registered = $item->created_at->diffForHumans();
        return $item;
    });

    return view('blog_views.post')->with(['post' => $post, 'comments' => $comments]);
}

I want to add paginate(5) on $comments before return it to view and keep this values accessible in the view.

{{ $comment->user->name }}    relationship returning the creator name of the comment
{{ $comment->registered }}    get the created field in controller

And the new one -> paginate links

{{$comments->links()}}

Source: Laravel

Leave a Reply