Benua
Benua

Reputation: 269

Laravel 5.4 delete table row and rows from related table

When i delete a row from a groups table, i want the function to also delete all relation mapping from table group_user. For example, if i delete group with id 4, all rows in group_user table with group_id 4 are deleted as well. Tables below:

 Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('phone');
            $table->boolean('approved')->default(false);
            $table->rememberToken();
            $table->timestamps();
        });
 Schema::create('groups', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('course_id');
            $table->timestamp('start_date')->nullable();
            $table->timestamp('end_date')->nullable();
            $table->timestamps();
        });
  Schema::create('group_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('group_id');
            $table->timestamps();
        });

Currently using this function in group controller, but it only deletes from groups table:

function deleteGroup($id){
		$group = Group::find($id);
		$group->delete();
		return redirect()->back();
	}

Upvotes: 0

Views: 1011

Answers (1)

Mamikon Arakelyan
Mamikon Arakelyan

Reputation: 166

If your table storage engine type is innodb you can try in your migrations to set correct relationships and all will be done in the database layer.

Schema::create('group_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('group_id');
        $table->timestamps();

        $table->foreign('user_id')
                ->references('id')
                ->on('users'))
                ->onDelete('cascade');
        $table->foreign('user_id')
                ->references('id')
                ->on('users'))
                ->onDelete('cascade');
    });

Upvotes: 1

Related Questions