php - 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?
Answer
Solution:
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.
Answer
Solution:
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.
Answer
Solution:
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.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: ftp_put(): can't open that file: no such file or directory
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.