Image

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


  1. <?php  
  2.   
  3. use Illuminate\Support\Facades\Schema;  
  4. use Illuminate\Database\Schema\Blueprint;  
  5. use Illuminate\Database\Migrations\Migration;  
  6.   
  7. class CreateUsersTable extends Migration  
  8. {  
  9.     /** 
  10.      * Run the migrations. 
  11.      * 
  12.      * @return void 
  13.      */  
  14.     public function up()  
  15.     {  
  16.         Schema::create('users'function (Blueprint $table) {  
  17.             $table->bigIncrements('id');  
  18.             $table->string('forename')->nullable();  
  19.             $table->string('surname')->nullable();  
  20.             $table->string('email')->unique();  
  21.             $table->string('password');  
  22.             $table->timestamp('email_verified_at')->nullable();  
  23.             $table->rememberToken();  
  24.             $table->timestamps();  
  25.         });  
  26.     }  
  27.   
  28.     /** 
  29.      * Reverse the migrations. 
  30.      * 
  31.      * @return void 
  32.      */  
  33.     public function down()  
  34.     {  
  35.         Schema::dropIfExists('users');  
  36.     }  
  37. }  

Now i want to use user_id as foreign key in my transactions table.


  1. <?php  
  2.   
  3. use Illuminate\Support\Facades\Schema;  
  4. use Illuminate\Database\Schema\Blueprint;  
  5. use Illuminate\Database\Migrations\Migration;  
  6.   
  7. class CreateTransactionsTable extends Migration  
  8. {  
  9.     /** 
  10.      * Run the migrations. 
  11.      * 
  12.      * @return void 
  13.      */  
  14.     public function up()  
  15.     {  
  16.         Schema::create('transactions'function (Blueprint $table) {  
  17.             $table->bigIncrements('id');  
  18.             $table->bigInteger('user_id')->unsigned()->nullable(); //index() is optional  
  19.             $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');  
  20.             $table->string('transactionId');  
  21.             $table->timestamps();  
  22.         });  
  23.     }  
  24.   
  25.     /** 
  26.      * Reverse the migrations. 
  27.      * 
  28.      * @return void 
  29.      */  
  30.     public function down()  
  31.     {  
  32.         Schema::dropIfExists('transactions');  
  33.     }  
  34. }  

 

Categories: PHP Tags: #Laravel,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.