Home > Net >  Store parent_id in laravel
Store parent_id in laravel

Time:04-10

I'm new to Laravel so I struggle. I have a comment system that worked perfectly fine but now I want to also add a reply system to it. So the way I decided to do it, is by adding a parent_id column to the comments table and then check if a comment has a parent. But I don't know how exactly the store method, in this case, should work. Here's my database set up for comments:

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->foreignId('post_id')->constrained()->cascadeOnDelete();
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->text('body');
        $table->timestamps();

        });
}

And now a set up for the reply column:

public function up()
{
    Schema::table('comments', function (Blueprint $table) {
        $table->unsignedBigInteger('parent_id')->nullable();

        $table->foreign('parent_id')->references('id')->on('comments');
    });
}

Model:

class Comment extends Model{
    use HasFactory;

    protected $guarded = [];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function author()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function replies() {
        return $this->hasMany('App\Comment', 'parent_id');
    }
}

Controller:

public function store(Post $post){

    request()->validate([
        'body' => 'required'
    ]);

    $post->comments()->create([
        'user_id' => request()->user()->id,
        'parent_id' => request()->get('id'),
        'body' => request('body')
    ]);

    return back();
}

I just don't know how exactly I can get parent_id in the store function so I would appreciate some suggetstions

CodePudding user response:

it should be the comment id that got the reply

something like this

$post->comments()->create([
    'user_id' => request()->user()->id,
    'parent_id' => request()->get('comment_id'),
    'body' => request('body')
]);

I hope it's helpful

  • Related