New migration methods in Laravel 7
Zubair Mohsin

Zubair Mohsin @zubairmohsin33

About: Full Stack Laravel Developer

Location:
Lahore, Pakistan
Joined:
Mar 4, 2019

New migration methods in Laravel 7

Publish Date: Mar 5 '20
22 4

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.

Comments 4 total

  • Sebastianus Sembara
    Sebastianus SembaraDec 17, 2020
    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

  • ilya
    ilyaMar 17, 2021

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

    • Zubair Mohsin
      Zubair Mohsin Mar 17, 2021

      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.

      • ilya
        ilyaMar 17, 2021

        ok.
        thank you

Add comment