DEV Community

Zubair Mohsin
Zubair Mohsin

Posted on

 

New migration methods in Laravel 7

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.

Top comments (4)

Collapse
 
ssembara profile image
Sebastianus Sembara • Edited
Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained();
});
Enter fullscreen mode Exit fullscreen mode

in script to define foreign key constraint like in Laravel 7 , How the script can detect references on table users or any table? there is not script has to define table_name

Collapse
 
zimenkoliyailya profile image
ilya

Hi
Do you know how to rename migration in laravel?
i mean command to rename migration
thank you.

Collapse
 
zubairmohsin33 profile image
Zubair Mohsin

Hi ilya, I am not aware of any command to rename migration in Laravel.
It's best to just recreate the migration or rename it manually.

Thanks.

Collapse
 
zimenkoliyailya profile image
ilya

ok.
thank you

12 Rarely Used Javascript APIs You Need

Practical examples of some unique Javascript APIs that beautifully demonstrate a practical use-case.