creating migration file with foreign key in laravel [ Updated ]

    By: Manu
    3 years ago

    First run this command

    php artisan make:migration CreateFavoriteTasksTable
    

    It will create a migration file in "database/migrations" folder.

    open this file in text editor. It will look like this.

    <?php
    
    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateFavoriteTasksTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('favorite_tasks');
        }
    }
    

    Now lets add code in UP function so we can create a table in database

    public function up()
    {
        Schema::create('favorite_tasks', function (Blueprint $table) {
    
            // for id field in table
            $table->bigIncrements('id');
    
            // we need to store user id 
            $table->unsignedinteger('user_id');
    
           // we need to store task id
            $table->unsignedinteger('task_id');
    
           // this will takecare of created_at and Updated_at
            $table->timestamps();
    
           // adding foreign key so task_id should reference to tasks table and id column
            $table->foreign('task_id')
                ->references('id')
                ->on('tasks');
          // adding foreign key for user so user_id should refer to id in users table
            $table->foreign('user_id')
                ->references('id')
                ->on('users');
        });
    }
    

    You need to modify code as you want change the name of table or columns as you like. Once all above done. Run this command

    php artisan migrate
    

    Thats it check database there should be a new table present with foreign keys setup.