Add foreign key to the migration file in Laravel

Here is how you add a foreign key to the migration file of Laravel

Let’s say you are creating a migration file for comments table, and it a Post model has hasMany relation with the Comment model. Then


        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->string('body');
            $table->unsignedBigInteger('post_id');
            $table->timestamps();

            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

        });

In the Post model you can define the relationship as follows


    public function comments(){
        return $this->hasMany(Comment::class);
    }

Site Footer