Laravel add foreign key constraint with migration in laravel.
----------------------------------------------
Add foreign key constraint with migration in laravel.You can use below code to make this work.
Users table schema
- <?php
- use Illuminate\Support\Facades\Schema;
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Database\Migrations\Migration;
- class CreateUsersTable extends Migration
- {
- /**
- * Run the migrations.
- *
- * @return void
- */
- public function up()
- {
- Schema::create('users', function (Blueprint $table) {
- $table->bigIncrements('id');
- $table->string('forename')->nullable();
- $table->string('surname')->nullable();
- $table->string('email')->unique();
- $table->string('password');
- $table->timestamp('email_verified_at')->nullable();
- $table->rememberToken();
- $table->timestamps();
- });
- }
- /**
- * Reverse the migrations.
- *
- * @return void
- */
- public function down()
- {
- Schema::dropIfExists('users');
- }
- }
Now i want to use user_id as foreign key in my transactions table.
- <?php
- use Illuminate\Support\Facades\Schema;
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Database\Migrations\Migration;
- class CreateTransactionsTable extends Migration
- {
- /**
- * Run the migrations.
- *
- * @return void
- */
- public function up()
- {
- Schema::create('transactions', function (Blueprint $table) {
- $table->bigIncrements('id');
- $table->bigInteger('user_id')->unsigned()->nullable(); //index() is optional
- $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
- $table->string('transactionId');
- $table->timestamps();
- });
- }
- /**
- * Reverse the migrations.
- *
- * @return void
- */
- public function down()
- {
- Schema::dropIfExists('transactions');
- }
- }