laravel - difference between foreignId() and unsignedBigInteger()
If you have a look in Blueprint.php you'll see both methods :
/**
* Create a new unsigned big integer (8-byte) column on the table.
*
* @param string $column
* @param bool $autoIncrement
* @return \Illuminate\Database\Schema\ColumnDefinition
*/
public function unsignedBigInteger($column, $autoIncrement = false)
{
return $this->bigInteger($column, $autoIncrement, true);
}
/**
* Create a new unsigned big integer (8-byte) column on the table.
*
* @param string $column
* @return \Illuminate\Database\Schema\ForeignIdColumnDefinition
*/
public function foreignId($column)
{
$this->columns[] = $column = new ForeignIdColumnDefinition($this, [
'type' => 'bigInteger',
'name' => $column,
'autoIncrement' => false,
'unsigned' => true,
]);
return $column;
}
So, by default it uses "bigInteger" column's type with "unsigned" set to true. In the end, they are the same.
The only difference would be that with "unsignedBigInteger" you can control if $autoIncrement is set to true or false, not with foreignId
Up to Laravel 6, we had to define foreign key constraints like
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
and that's Laravel 7 syntax
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});