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); }
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners