How do you generate migrations?
How do you generate migrations?
To generate migrations in Laravel, you can use the built-in Artisan command make:migration
. This command helps you create a new migration file, which will be placed in the database/migrations
directory of your Laravel project. Each migration file contains a timestamp in its filename to determine the order of migrations. Here is a step-by-step guide on how to generate migrations:
Create a Migration File:
To create a new migration file, you can use the following command:
php artisan make:migration create_users_table
This command will generate a migration file with a timestamp prefix in the database/migrations
directory. Laravel will attempt to determine the table name and the migration action from the filename.
Specify Table and Action:
If Laravel cannot determine the table name or action, you can specify them using the --table
and --create
options:
php artisan make:migration add_votes_to_users_table --table=users
php artisan make:migration create_users_table --create=users
Custom Path:
You can also specify a custom path for the generated migration file using the --path
option:
php artisan make:migration create_users_table --path=app/database/migrations
A migration class contains two main methods: up
and down
.
up
Method:
This method is used to define the operations to be performed when the migration is run. For example, creating a new table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
down
Method:
This method is used to reverse the operations performed by the up
method. For example, dropping the table:
public function down()
{
Schema::dropIfExists('users');
}
...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào