Ad

How To Access A Variable Saved In The Store Method?

- 1 answer

I'm using nested set comments (Kalnoy package) in my project and I'm stuck at creating children comments. I created two different method for both type of comments.

Saving root comments works fine:

public function storeComments(Request $request, Post $post)
    {
        $comment = Comment::create(
            [
            'body' => request('body'),
            'user_id' => auth()->id(),
            'post_id' => $post->id,
            ]
        )->saveAsRoot();

        return back();
    }

However children comments are still saved as root comments.

public function storeNestedComments(Request $request, Comment $comment, Post $post)
    {
        $comment->children()->create(
            [
            'body' => request('body'),
            'user_id' => auth()->id(),
            'parent_id' => $comment->id,
            'post_id' => $post->id,
            ]
        );

        return back();
    }

This $comment variable in the second method is naturally null. How can I access the comment that was saved as root?

Update: saveAsRoot() logic

public function saveAsRoot()
    {
        if ($this->exists && $this->isRoot()) {
            return $this->save();
        }

        return $this->makeRoot()->save();
    }
Ad

Answer

@Amaury gave me a hint :)

I changed my route to include the root comment id

Route::post('/posts/{post}/{comment}/nestedcomments', '[email protected]');

Passed that id to the method, and associated the child id with the parent.

public function storeNestedComments($parent_comment_id)
{
    $comment = Comment::where('id', $parent_comment_id)->first();

    $nestedComment = Comment::create(
        [
        'body' => request('body'),
        'user_id' => auth()->id(),
        'parent_id' => $parent_comment_id,
        'post_id' => $comment->post_id,
        ]
    );

    $nestedComment->parent()->associate($comment)->save();

    return back();
}
Ad
source: stackoverflow.com
Ad