skip to Main Content

While designing the database for a laravel software using MYSQL, is assigning foreign keys relevant or does Laravel take care of that "Software side".

In the migration we have something like

Table Example:

$table->unsignedBigInteger('user_id');

should i modify the example table in phpmyadmin and make user_id a foreign key? is there a better way or is this not relevant or necessary?

2

Answers


  1. You should define foreign key constraints in your migration. When using code base you should make all the changes using migrations.

    Additionally by defining foreign key you actually build a relation between 2 tables otherwise this relation will be at code level. When relation is built database will restrict to have only values which actually exists in main table. Using foreign key you can also do cascading (on update and delete) at db level.

    Reference what are the advantages of defining a foreign key

    Why should I use foreign keys in database?

    Login or Signup to reply.
  2. if use Laravel 7 ,you can use this short that is a column name user_id foreign to ID user in the table users :

    $table->foreignId('user_id')->nullable()->constrained()->onDelete('cascade');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search