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 reverse htmlentities() / What is the opposite of htmlentities()?

How to query mysql using PDO in PHP?

How to group a SQL statement in brackets/parenthesis

Point all requests to one PHP file

How to access the Laravel's route parameters outside of the controller?

What are Template literals (Template strings) in JS?

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

Why should you update APP_URL from from http://localhost?

How to namespace a Laravel route group?

How to return JSON data to the user in Laravel?