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 an object or variable is an array, in JS?

What are route patterns in Laravel?

What are Apache MPMs?

What are the SPL Iterators in PHP?

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

How to see all of the options for an artisan command?

How to block access to certain referrers in Apache using .htaccess

How to show (or log) all SQL queries executed by Laravel

How to round a number in JS?

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?