You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel评论回复系统中store方法如何获取parent_id?

Hey there! Let's get your comment reply functionality sorted out—you're already on the right track with the parent_id approach, just a few small tweaks needed to make it work smoothly.

First, Fix the store Method Logic

Right now, you’re using request()->get('id') to fetch the parent comment ID, but that’s likely not matching what your frontend is sending over. Let’s adjust that, plus add proper validation to ensure parent_id is valid when provided:

public function store(Post $post){
    request()->validate([
        'body' => 'required|string',
        'parent_id' => 'nullable|exists:comments,id' // Ensure parent_id is either null or a valid comment ID
    ]);

    $post->comments()->create([
        'user_id' => auth()->id(), // Shorter, cleaner way to get the authenticated user's ID
        'parent_id' => request('parent_id'), // Match the input name we'll set up in the frontend
        'body' => request('body')
    ]);

    return back();
}

Next, Update Your Frontend to Send the parent_id

You need to make sure when someone clicks "Reply" on a comment, the form submits the ID of the comment they’re replying to. Here’s a simple example using Blade templates:

<!-- Main comment form (for top-level comments, no parent) -->
<form action="{{ route('comments.store', $post) }}" method="POST">
    @csrf
    <textarea name="body" placeholder="Add a comment..." required></textarea>
    <button type="submit">Post Comment</button>
</form>

<!-- Render existing comments and their reply forms -->
@foreach($post->comments->whereNull('parent_id') as $comment)
    <div class="comment">
        <p><strong>{{ $comment->author->name }}:</strong> {{ $comment->body }}</p>
        <button class="reply-toggle">Reply</button>
        
        <!-- Hidden reply form (show when "Reply" is clicked) -->
        <form action="{{ route('comments.store', $post) }}" method="POST" class="reply-form" style="display: none; margin-left: 2rem;">
            @csrf
            <input type="hidden" name="parent_id" value="{{ $comment->id }}"> <!-- This passes the parent comment ID -->
            <textarea name="body" placeholder="Add a reply..." required></textarea>
            <button type="submit">Post Reply</button>
        </form>

        <!-- Render replies to this comment -->
        @foreach($comment->replies as $reply)
            <div class="comment" style="margin-left: 2rem;">
                <p><strong>{{ $reply->author->name }}:</strong> {{ $reply->body }}</p>
            </div>
        @endforeach
    </div>
@endforeach

<!-- Optional: Add JS to toggle reply forms -->
<script>
    document.querySelectorAll('.reply-toggle').forEach(btn => {
        btn.addEventListener('click', () => {
            const form = btn.nextElementSibling;
            form.style.display = form.style.display === 'none' ? 'block' : 'none';
        });
    });
</script>

Bonus: Add a parent Relationship to Your Comment Model

To make it easier to access the parent comment (if you ever need to display context for a reply), add this to your Comment model:

public function parent() {
    return $this->belongsTo(Comment::class, 'parent_id');
}

Now you can do things like $reply->parent->body to fetch the text of the comment being replied to.

Quick Key Notes

  • The nullable rule on parent_id lets top-level comments save with a null value, which is exactly how you’ll distinguish them from replies.
  • Double-check your route for storing comments is correctly set up to accept the Post model parameter (it looks like you already have this covered).
  • auth()->id() is just a cleaner alternative to request()->user()->id—both work, but the former is more concise.

That’s it! Your database setup is already correct, so once you adjust the form and controller, replies will start saving with the proper parent_id and you can display them nested under their parent comments.

内容的提问来源于stack exchange,提问作者Local dude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:32:46