New migration methods in Laravel 7

Zubair Mohsin - Mar 5 '20 - - Dev Community

id()

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

$table->bigIncrements('id');
Enter fullscreen mode Exit fullscreen mode

With Laravel 7 release, there is more cleaner syntax 🔥

$table->id();
Enter fullscreen mode Exit fullscreen mode

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);
    }
Enter fullscreen mode Exit fullscreen mode

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');
});
Enter fullscreen mode Exit fullscreen mode

Behold the Laravel 7 syntax 🤯

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

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;
    }
Enter fullscreen mode Exit fullscreen mode

Read more about these in the docs.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player