Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

297
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda