laravel migration best way to add foreign key laravel migration best way to add foreign key laravel laravel

laravel migration best way to add foreign key


Firstly you have to make your user_id field an index:

$table->index('user_id');

After that you can 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 firstly and do everything from scratch.

On down() function you have to do this and then on up() do what I've wrote above:

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


Schema::create('roles',function(Blueprint $table){    $table->bigIncrements('id');    $table->string('name');    $table->timestamps();});Schema::create('permissions',function(Blueprint $table){    $table->unsignedBigInteger('role_id');    $table->foreign('role_id')->references('id')->on('roles');    $table->string('permission');});


$table->integer('user_id')->unsigned();$table->foreign('user_id')->references('id')->on('users');

In this example, we are stating that the user_id column references the id column on the users table. Make sure to create the foreign key column first! The user_id column is declared unsigned because it cannot have negative value.

You may also specify options for the "on delete" and "on update" actions of the constraint:

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

To drop a foreign key, you may use the dropForeign method. A similar naming convention is used for foreign keys as is used for other indexes:

$table->dropForeign('posts_user_id_foreign');

If you are fairly new to Laravel and Eloquent, try out the Laravel From Scratch series available on laracasts. It is a great guide for beginners.