0

i am trying to delete Model from Model table and all of its comments from Comments table...my current code delete the model but not its comments from the other table...

Here is my destroy function

public function destroy(Request $request,CadModel $cadmodel)
    {
        $cadmodel->load('comments')->delete();
        $request->session()->flash('message.level', 'success');
        $request->session()->flash('message.content', 'File Deleted Successfully!');
        return redirect()->route('dashboard');
    }

Here is the relationship i defined in CadModel Laravel Model...

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

Please Reply and suggest me a solution to delete both..Model and its Comments

MA-2016
  • 653
  • 3
  • 10
  • 30

1 Answers1

0

In your migration, set your related comments to be deleted if the model is deleted with onDelete('cascade').

Example:

/**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('comments_model', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('comment_id')->unsigned();
            $table->integer('model_id')->unsigned();

            $table->foreign('comment_id')->references('id')->on('comments')->onDelete('cascade');
            $table->foreign('model_id')->references('id')->on('models')->onDelete('cascade');
        });
    }
kerrin
  • 3,376
  • 1
  • 26
  • 36