📜  php artisan make migration - PHP (1)

📅  最后修改于: 2023-12-03 14:45:10.481000             🧑  作者: Mango

PHP Artisan Make Migration

PHP Artisan is a command-line interface tool provided by Laravel, a popular PHP web application framework. One of its features is the ability to create a new database migration with the make:migration command.

Command Syntax

To create a new migration, run the make:migration command followed by the name of the migration and any optional flags:

php artisan make:migration CreateUsersTable --create=users

The above command will create a new migration file in the database/migrations directory with the name create_users_table.php. It will also add code to create a new users table in the database.

You can also specify the --table option instead of --create to add columns to an existing table:

php artisan make:migration AddLastNameToUsersTable --table=users

This will create a new migration file with the name add_last_name_to_users_table.php. It will add code to add a new last_name column to the users table.

Migration Code

The code generated by the make:migration command creates a new class that extends the Migration class provided by Laravel. The class contains two important methods:

  • up(): This method contains the code that should be executed when the migration is run.
  • down(): This method contains the code that should be executed when the migration is rolled back.

Here is an example of a migration that creates a new users table:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

In the up() method, a new users table is created with various columns using the Schema::create() method. In the down() method, the users table is dropped using the Schema::dropIfExists() method.

Conclusion

The php artisan make:migration command is a powerful tool that allows PHP developers to quickly generate new database migrations for their Laravel applications. By understanding its syntax and generated code, developers can create new migrations with ease and confidence.