Search code examples
laravelforeign-keysmigration

laravel migration best way to add foreign key


Simple question: I'm new to Laravel. I have this migration file:

Schema::create('lists', function(Blueprint $table) {
    $table->increments('id'); 
    $table->string('title', 255);
    $table->integer('user_id')->unsigned(); 
    $table->foreign('user_id')->references('id')->on('users'); 
    $table->timestamps();
});

I want to update it to add onDelete('cascade').

What's the best way to do this?


Solution

  • Inside the up() function

    First, make your user_id field an index:

    $table->index('user_id');
    

    After that you create a foreign key with an action on cascade:

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

    If you want to do that with a new migration, you have to remove the index and foreign key first, then do everything from scratch.

    Inside the down() function

    $table->dropForeign('lists_user_id_foreign');
    $table->dropIndex('lists_user_id_index');
    $table->dropColumn('user_id');