On Cascade Delete ( real example )
https://stackoverflow.com/questions/26820788/add-on-delete-cascade-to-existing-column-in-laravel
1) first projects needs to be created :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('project_name') ;
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('projects');
}
}
2) then the tasks table
<?php /// 2017_08_19_154845_create_tasks_table
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->integer('project_id')->unsigned(); // THIS NEEDS TO BE UNSIGNED, its a foreign key
$table->string('task_title');
$table->text('task') ;
$table->integer('priority')->default(0) ;
$table->boolean('completed')->default(0) ;
$table->timestamps();
});
/*
Delete Project Tasks Content when deleting a project
reference the project ID on Projects, cascade down and delete everything
If the 'Project' is deleted, delete all the tasks that belong to that project".
*/
// THIS DOES THE MAGIC
Schema::table('tasks', function (Blueprint $table) {
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade') ;
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tasks');
}
}
=================== EXTRA =========================
after running the migration you will see the relationship at the end of the file
when you export the .sql file:
-- Constraints for table `tasks`
--
ALTER TABLE `tasks`
ADD CONSTRAINT `tasks_project_id_foreign` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`) ON DELETE CASCADE;
COMMIT;