What kind of database field type should you (normally) use for foreign keys?

Laravel: What kind of database field type should you (normally) use for foreign keys?

For most cases you will want to use unsignedInteger for foreign keys. The actual answer is that the foreign key should be the same type as the primary key on the main table, which is normally an unsignedInteger.

Even if it isn't an actual foreign key you should be using this for anything that relates to another unsignedInteger. It is marginally quicker than just using integer.

  1. $table->unsignedInteger('user_id');
  2. $table->foreign('user_id')->references('id')->on('users');

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about What kind of database field type should you (normally) use for foreign keys?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to check if a string contains a certain substring?

Remove trailing slash (redirect to remove trailing slash) in .htaccess

How to make Apache force download of files (in .htaccess)

How to exclude URLs from the Laravel CSRF protection?

How to get the last character of a string in JS?

How to add comments in PHP

How to group a SQL statement in brackets/parenthesis

What are Template literals (Template strings) in JS?

How to get a route to directly show a view?

How to do comments in Blade files?