Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested sets with Baum and Laravel Commentable: children comments are being inserted without the commentable id and type

I am trying to achieve multi threaded comments using Laravel Commentable which uses Nested Sets with Baum

I have managed to make the root comments work, however when I reply to a comment, the record in the database gets inserted without commentable_id and commentable_type so there's no way in knowing whether the reply to that comment is for App\Post or App\Product because these 2 fields are empty and I can't seem to understand why.

Tables

users: id, name, email...
posts: id, user_id, subreddit_id...
comments: id, user_id, parent_id, lft, rgt, depth, commentable_id, commentable_type

Routes

Route::post('comments/{post}', ['as' => 'comment', 'uses' => 'PostsController@createComment']);
Route::post('comments/{comment}/child', ['as' => 'child-comment', 'uses' => 'PostsController@createChildComment']);

Methods in PostController

public function createComment($id) {

    $post = Post::with('user.votes')->with('subreddit.moderators')->where('id', $id)->first();

    $comment = new Comment;
    $comment->body = Input::get('comment');
    $comment->user_id = Auth::id();

    $post->comments()->save($comment);
}

public function createChildComment(Post $post){
    $parent = Comment::find(Input::get('parent_id'));

    $comment = new Comment;
    $comment->body = Input::get('child-comment');
    $comment->user_id = Auth::id();
    $comment->save();
    $comment->makeChildOf($parent);

}

View for root comments and children comments

<-- This is for root comments --/>
{!! Form::open(['route' => ['comment', $post]]) !!}
@foreach($comments as $comment)

@endforeach
{!! Form::close() !!}

<-- This is for children comments --/>
{!! Form::open(['route' => ['child-comment', $comment]]) !!}
<input type="hidden" name="parent_id" value="{{ $comment->id }}"/>
{!! Form::close() !!}
like image 524
Halnex Avatar asked Oct 13 '15 13:10

Halnex


1 Answers

Off the top of my head, wouldn't you make the child before you $comment->save() the comment, so its in the correct state before it hits the database with save.

Edit: Try this:

public function createChildComment(Post $post){
    $parent = Comment::find(Input::get('parent_id'));

    $comment = new Comment;
    $comment->body = Input::get('child-comment');
    $comment->user_id = Auth::id();
    $comment->save();
    $comment->makeChildOf($parent);
    $comment->save();

}

Currently I'm under the belief that the change that $comment->makeChildOf($parent) does would get thrown.

like image 186
Paul Stanley Avatar answered Sep 23 '22 19:09

Paul Stanley