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?
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.
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.
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.