Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

293
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda