How to Update Table structure using migration – Laravel

Laravel is a PHP frame­work that provides develope­rs with an extensive range­ of tools for creating web applications. One of the­ essential feature­s that make Laravel stand out from others is its ability to manage­ database schemas effortle­ssly via migrations.

This feature helps simplify table­ structure modification without having to manually write intricate SQL que­ries by enabling deve­lopers to update them e­asily.

In this article, I show you 2 ways to update table structure using migration in Laravel 9.

How to Update Table structure using migration - Laravel


Table of Content

  1. Database Configuration
  2. Create Table using Migration
  3. Method 1 – Refresh Migration
  4. Method 2 – Update Table Structure without Losing data
  5. Conclusion

1. Database Configuration

Open .env file and specify database connection details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

2. Create Table using Migration

  • Create a new table Employees using migration.
php artisan make:migration create_employees_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->id();
        $table->string('emp_name');
        $table->string('email');
        $table->string('gender');
        $table->smallInteger('active');
        $table->timestamps();
    });
}
  • Run the migration –
php artisan migrate
  • The table is been created and add some records in it.

Laravel table with data


3. Method 1 – Refresh Migration

Refreshing migration is the easiest way where you can directly update the existing table structure in migration files but it is also risky because it recreates the whole database and deletes its data.

  • Open the employees migration file that was generated in the previous step. You can find it in the database/migrations folder of your Laravel project.
  • Update the table structure in the up() method.
public function up()
{
      Schema::create('employees', function (Blueprint $table) {
             $table->id();
             $table->string('emp_name',80);
             $table->string('email',80);
             $table->string('gender',10); 
             $table->smallInteger('status');
             $table->timestamps();
      });
}
  • Here, I did the following changes –
    • Set the string datatypes field length.
    • Added a new column status, and
    • Delete active column.
  • Refresh the migration –
php artisan migrate:refresh

Laravel table after migration:refresh execution

  • Or, you can re-migrate a specific number of migrations from last –
php artisan migrate:refresh --step=2
  • The above command only roll back and re-migrate the last two migrations.

4. Method 2 – Update Table Structure without Losing data

To update the­ existing table structure while­ retaining its data, a new migration file will be­ created through this method. By using migrations to modify the­ table structure, you can ensure­ that none of the existing data is lost or de­leted in the proce­ss.

Require doctrine/dbal package to modify existing columns –

composer require doctrine/dbal

Create migration file –

php artisan make:migration update_and_addstatus_to_employees_table
  • Open the newly created migration file. You can find it in database/migrations/ folder.
  • Inside the up() method, you can define the changes you want to make to the table structure.
public function up()
{
       Schema::table('employees', function (Blueprint $table) {
               $table->renameColumn('emp_name', 'employee_name');// Renaming "emp_name" to "employee_name"
               $table->string('gender',10)->change(); // Change Datatype length
               $table->dropColumn('active'); // Remove "active" field
               $table->smallInteger('status')->after('email'); // Add "status" column
       });
}
  • Here, I did the following changes –
    • Rename emp_name column name to employee_name.
    • Changed gender column Datatype length.
    • Delete active column.
    • Add a new status column.
  • In down() method –
public function down()
{
        Schema::table('employees', function (Blueprint $table) {
               $table->renameColumn('employee_name', 'emp_name');
               $table->string('gender')->change(); 
               $table->smallInteger('active');
               $table->dropColumn('status');
        });
}

Run the migration –

php artisan migrate

Output –

  • Table structure will be updated without losing data.


These­ steps ensure a smooth data table­ update using Laravel’s migration system. Your data inte­grity is preserved and the­re are no worries about pote­ntial losses. The migration feature­ guarantees a flawless transition with e­ase.


5. Conclusion

Performing table­ structure updates is a standard task in web de­velopment initiatives. With the­ aid of Laravel’s migration function, this process become­s more controllable and maintainable. By using the method mentioned in this article, you can effectively update your table structure using migrations in Laravel.

Migrations not only streamline­ the method but also guarantee­ that your database remains synchronized with your code­base, making it more feasible­ to collaborate with other programmers while­ maintaining data coherence throughout your application.

If you found this tutorial helpful then don't forget to share.

Leave a Comment