Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
Is it necessary to define foreign key constraint in laravel migrations?

I have seen many people write migrations without defining foreign key constraints including jeffrey way in his videos. For example,

Schema::create('post',function(Blueprint $table){
    $table->id();
    $table->integer('user_id')->index();
    $table->text('body');
    //
});

Here, there is no foreign key constraint defined like the following

$table->foreign('user_id')->references('id')->on('users');

I always define foreign key because that's how you maintain the relationships and integrity between tables. But I have seen many videos where they do not define the foreign key. Is there any specific reason behind it?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Foreign key constraints make your database consistent. I don't know any another way to do something like cascading. You should read about this too. Consider a scenario where you delete the parent element and child element is just sitting there in some related table. huh! Now that can break your app.

PS: It's not necessary but SHOULD be done.

over 4 years ago · Santiago Trujillo Report

0

It's not necessary but we should index everything we use on where(). So yes, you should cretae foreign keys, this way you create indexes and link the tables.

over 4 years ago · Santiago Trujillo Report

0

The only reasons to not use these keys are if you don't need consistency in your database or you are sure that your framework/code is not prone to these referential errors. But as seen in the videos, the foreign keys do not have to be defined to have functioning relations in your laravel app.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!