How to update Laravel migrations

Upgrade Laravel migrations: an example showing how to easily update databases with new changes.

Updating a Laravel migration is an important part of keeping your application up to date. You can update an existing migration to modify or add new columns or make other changes to the database. In this tutorial, we'll look at how to update a Laravel migration using an example.

Step 1: Create a New Migration File

In order to update a migration, you'll need to create a new migration file. To do this, you can use the make:migration Artisan command. This command will generate a new migration file in the database/migrations directory. In this example, we'll create a new migration called add_user_address_column:

php artisan make:migration add_user_address_column

Once the command has been executed, you'll see a new migration file in the database/migrations directory. This file contains a up() and down() method. The up() method is used to add new columns and make other changes to the database. The down() method is used to undo the changes made in the up() method.

Step 2: Add New Columns

In this example, we'll add a new address column to the users table. To do this, we'll use the Schema::table() method in the up() method. The Schema::table() method takes two arguments: the name of the table and a closure containing the columns to add. We'll also use the $table->string() method to add a string type column:

Schema::table('users', function ($table) {
    $table->string('address');
});

This will add a new address column to the users table. We can also set a default value for the column using the ->default() method:

Schema::table('users', function ($table) {
    $table->string('address')->default('unknown');
});

Once you've added the columns, you can run the migration using the migrate Artisan command:

php artisan migrate

This will update the database with the changes made in the migration file. If you need to undo the changes, you can use the rollback Artisan command to rollback the migration:

php artisan migrate:rollback

This will undo the changes made in the migration and remove the address column from the users table.

Updating a Laravel migration is an important part of keeping your application up to date. With the steps above, you can easily update a migration and make changes to the database. You can also use the make:migration command to generate a new migration file and the migrate and rollback commands to update and undo the changes.

Answers (0)