Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel - difference between foreignId() and unsignedBigInteger()

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 for unsignedBigInteger

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');
like image 626
h-kys Avatar asked Apr 02 '20 23:04

h-kys


2 Answers

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

like image 191
Octet Avatar answered Sep 18 '22 11:09

Octet


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();
});
like image 26
DOBss Avatar answered Sep 18 '22 11:09

DOBss