h-kys
h-kys

Reputation: 175

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');

Upvotes: 15

Views: 42436

Answers (4)

DOBss
DOBss

Reputation: 197

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();
});

Upvotes: 18

Brilantin
Brilantin

Reputation: 11

Alias meaning : "used to indicate that a named thing is also known or more familiar under another specified name."

So it is basically the same!

Upvotes: 0

Octet
Octet

Reputation: 1041

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

Upvotes: 24

Ezrab_
Ezrab_

Reputation: 983

Yes alias means it’s the same.

Upvotes: 0

Related Questions