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?
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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With