如何在laravel 5中删除父记录时不删除子记录?

I have a record which is having a child record. Now When I try to delete that record it should say that "You couldn't delete this record;because its having a child record". How to do this is laravel 5??

Eg: Equipment record have a department column and when I try to delete this equipment record it should give a message that, "this record is having a department. you could not delete it".

This is my migration script:

public function up()
{
Schema::create('equipment', function(Blueprint $table){
$table->string('id', 32)->unique()->index();
$table->string('equipment_no',32);
$table->string('organization_id',32)->index();
$table->foreign('organization_id')->references('id')->on('organization')->onDelete('cascade')->onUpdate('cascade');
$table->string('customer_id',32)->index();
$table->foreign('customer_id')->references('id')->on('customer')->onDelete('cascade')->onUpdate('cascade');
$table->string('equipment_type',32);
$table->string('equipment_category_id',32)->index();
$table->foreign('equipment_category_id')->references('id')->on('equipment_category')->onDelete('cascade')->onUpdate('cascade');
$table->string('equipment_model_id',32)->index();
$table->foreign('equipment_model_id')->references('id')->on('equipment_model')->onDelete('cascade')->onUpdate('cascade');
$table->string('equipment_fabricat_id',32)->index();
$table->foreign('equipment_fabricat_id')->references('id')->on('equipment_fabricat')->onDelete('cascade')->onUpdate('cascade');
$table->string('department_id',32)->index();
$table->foreign('department_id')->references('id')->on('department')->onDelete('cascade')->onUpdate('cascade');
$table->text('location');
$table->string('inspection_interval',45);
$table->foreign('added_by')->references('id')->on('user')->onDelete('cascade')->onUpdate('cascade');
$table->SoftDeletes();
$table->timestamps();
});
}

and my destroy function on controller page is:

public function destroy($id)
{
$equipment = Equipment::findOrFail($id);
$equipment->delete();
return Redirect::route($this->route)->with($this->success, trans($this->deletemsg));
}

Can anyone help me with it??

That's the right way :-)

It's because there are relationships (foreign keys). By deleting your parent record, your child records are 'zombies' (they are floating).

If you still want to do that:

  • Remove the foreign keys
  • Change you storage engine to MyISAM (if you're using MySQL database)

An alternative is removing the child records too. Example table:

CREATE TABLE rooms (
    room_no int(11) NOT NULL AUTO_INCREMENT,
    room_name varchar(255) NOT NULL,
    building_no int(11) NOT NULL,
    PRIMARY KEY (room_no),
    KEY building_no (building_no),
    CONSTRAINT rooms_ibfk_1 
    FOREIGN KEY (building_no) 
    REFERENCES buildings (building_no) 
    ON DELETE CASCADE
) ENGINE=InnoDB;