alekv's avatar
Level 2

Creating comments pagination

Hi everyone!

I have a issue with creating eloquent relationship and comment paggination.

This is a code:

Recipe.php model:

public function comments()
{
    return $this->hasMany(Comment::class);
}

}

Comment.php model:

public function show()
{
    return $this->belongsTo(Recipe::class, 'id');
}

Currently on the view I show comments this way, and it is working:

    @foreach ($recipe->comments()->orderBy('created_at', 'desc')->get() as $comment)
        <x-recipes.recipe-comment :comment="$comment" />
    @endforeach

Now I want to make method show() and to paginate comments.

How to make method show() to show comments and to paginate?

0 likes
5 replies
LaryAI's avatar
Level 58

To paginate comments, you can use Laravel's built-in pagination method. Here's an example of how you can modify your code to achieve this:

In your Recipe.php model, modify the comments() method to include pagination:

public function comments()
{
    return $this->hasMany(Comment::class)->orderBy('created_at', 'desc');
}

In your view, replace the current foreach loop with the following code:

@foreach ($recipe->comments()->paginate(10) as $comment)
    <x-recipes.recipe-comment :comment="$comment" />
@endforeach

This will display 10 comments per page. You can adjust the number as needed.

In your Comment.php model, remove the show() method as it is not needed for this functionality.

That's it! Your comments should now be paginated.

tykus's avatar
tykus
Best Answer
Level 104

First, lets fix the reciprocal relationship:

// Recipe model
public function comments()
{
    return $this->hasMany(Comment::class);
}
// Comment model
public function recipe()
{
    return $this->belongsTo(Recipe::class);
}

Ideally, we would organize the data in the Controller rather than in the view - simply passing a separate $comments variable to the view instead:

public function show(Recipe $recipe)
{
    $comments = $recipe->comments()->latest()->paginate();
    return view('recipes.show', compact('recipe', 'comments'));
}

Then in the view:

@foreach ($comments as $comment)
    <x-recipes.recipe-comment :comment="$comment" />
@endforeach
2 likes
alekv's avatar
Level 2

@tykus thank you!

I changed controller to this, and it work this way:

public function show(Recipe $recipe)
{
    return view('recipes.show', [
        'recipe' => $recipe,
        'comments' => $recipe->comments()->orderByDesc('created_at')->paginate(5)
    ]);
}
tykus's avatar

@alekv same difference really...

Please mark the thread closed if your problem is solved.

alekv's avatar
Level 2

@tykus yeah, simple and perfect solution... Thanks again, I will close the thread now.

Please or to participate in this conversation.