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 block access to certain referrers in Apache using .htaccess

How to review blog posts (written by other users) before they get published on your WordPress blog?

How to use subdomains as parameters in your routes (or in your web.php file)

What is Agile software development?

How to replace whitespace with a single space

How to destroy or remove a cookie in PHP

How to get the type of a variable in JS?

How to set environmental variables in your .htaccess file

How to namespace a Laravel route group?

Force trailing slash (redirect if no trailing slash exists) in .htaccess