Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 741
reshma kr Avatar asked Oct 18 '14 07:10

reshma kr


People also ask

How do I add a column in Laravel migration without losing data?

database\migration\add_new_column_to_products_table.php Now you can run migrate command to add this new field. Simply you can run below command to auto add a new field. Hope it can help you. Laravel Migration example tutorial, in this tutorial you have learned how to add new column to a table without losing data.

Should I use migration in Laravel?

In Laravel, Migration provides a way for easily sharing the schema of the database. It also makes the modification of the schema much easier. It is like creating a schema once and then sharing it many times.

What methods are used in Laravel for migration?

A migration class contains two methods: up and down . The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method.


1 Answers

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'); 
like image 108
Nerijus Masikonis Avatar answered Sep 24 '22 18:09

Nerijus Masikonis