For example, we have a table called customers
and we want to add a new column called user_id
as foreign key to the users
table. Here is how to do it.
- Create a migration file
1
php artisan make:migration add_user_id_to_customers_table --table=customers
- Add the following code to the migration file
1 2 3 4 5 6 7
public function up() { Schema::table('customers', function (Blueprint $table) { $table->unsignedBigInteger('user_id')->before('created_at'); $table->foreign('user_id')->references('id')->on('users')->onDelete('SET NULL') }); }
1 2 3 4 5 6 7
public function down() { Schema::table('customers', function (Blueprint $table) { $table->dropForeign(['user_id']); $table->dropColumn('user_id'); }); }
- Run the migration
1
php artisan migrate