New to Laravel
What is the difference between foreignId() and unsignedBigInteger() while linking tables
$table->unsignedBigInteger('user_id');
$table->foreignId('user_id');
I've tried both and they all worked.
According to the documentation it says:
The
foreignId
method is an alias forunsignedBigInteger
but what does alias mean? Does it mean they are the same?
PS: I didn't use the code in the documentation but only
$table->unsignedBigInteger('user_id');
and/or
$table->foreignId('user_id');
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 needed to define foreign key constraint 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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With