1

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?

RG Servers
  • 1,726
  • 2
  • 11
  • 27
  • 2
    its not necessary but its nice for data integrity; the database is a good place for enforcing such a constraint – lagbox Aug 25 '20 at 07:43
  • @lagbox thank you very much, but does it effect the database loading or performance in anyway? – RG Servers Aug 25 '20 at 07:44
  • 1
    If you define the name as `user_id`, then Laravel model can detect as `users` table `id`. But if you define any other name, then you need to tell laravel about the foreign key name, while making relationship on model – STA Aug 25 '20 at 07:46
  • 2
    @KhalilGhanem it does affect, because declaring a foreign key in MySQL will create an index that will let the base load more effectively. On a small database, the difference is negligeable, but on bigger you can really see a difference in seconds. – Lyzvaleska Aug 25 '20 at 07:49

2 Answers2

2

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?

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
-1

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');
Abdulmajeed
  • 552
  • 7
  • 8