loading...

New migration methods in Laravel 7

zubairmohsin33 profile image Zubair Mohsin ・1 min read

id()

Up to Laravel 6, we used to put the id column on tables in our migrations like below:

$table->bigIncrements('id');

With Laravel 7 release, there is more cleaner syntax 🔥

$table->id();

Let's also take a look at its definition:

    /**
     * Create a new auto-incrementing big integer (8-byte) column on the table.
     *
     * @param  string  $column
     * @return \Illuminate\Database\Schema\ColumnDefinition
     */
    public function id($column = 'id')
    {
        return $this->bigIncrements($column);
    }

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

Behold the Laravel 7 syntax 🤯

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained();
});

one-liner! How cool is that 🥳

Definition of method:

    /**
     * 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;
    }

Read more about these in the docs.

Posted on by:

Discussion

markdown guide