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.
Top comments (4)
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
Hi
Do you know how to rename migration in laravel?
i mean command to rename migration
thank you.
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.
ok.
thank you