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 user is logged in, inside a blade file?

How to prevent Eloquent from adding created_at or updated_at timestamps?

How to namespace a Laravel route group?

How to provide a default model object for relationships?

How to sort an array of dates and times?

Point all requests to one PHP file

How to set up an alias to map one directory to another destination

How to merge/concat two arrays together in JS?

What is the spaceship operator (<=>) in PHP?

How to round a number in JS?