This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Introducing DigitalOceans General Purpose & CPU Optimized Servers on Cloudways Flexible. Learn More

The Ultimate Guide to Laravel Migrations

Updated on February 19, 2025

10 Min Read
laravel migrations

Key Takeaways:

  • Laravel migrations provide a structured and version-controlled way to manage database schema changes, ensuring consistency across environments.
  • Using migrations simplifies database management, allows for easy rollbacks, and supports collaboration among developers, leading to a more efficient development workflow.

Laravel Migrations are fundamental for managing database changes in Laravel applications. They offer an organized approach to synchronize your database with your application’s codebase across various environments.

Imagine your application evolving over time, requiring changes to the database structure or the addition of new tables. Migrations prevent this process from becoming a manual, error-prone ordeal.

Each migration file is timestamped, ensuring a clear history of changes executed in the order they were created. This simplifies tasks like rolling back to previous states or applying changes incrementally.

This article provides a comprehensive tutorial on Laravel Migration, highlighting its importance, benefits, and practical usage. Whether you’re a beginner or an experienced developer, this guide equips you with the knowledge to effectively utilize Laravel Migration.

What are Laravel Migrations?

Laravel Migration is a set of instructions that define the changes you want to make to your database schema. These changes can include creating new tables, altering existing tables, adding or modifying columns, and seeding the database with initial data.

By encapsulating these changes within migration files, Laravel ensures that your database schema remains synchronized with your application’s codebase, making it easier to manage database changes across different development environments and deployment stages.

Laravel allows you to carry out migrations without worrying about the specific database system you’re using, whether it’s MySQL, PostgreSQL, SQLite, or others supported by Laravel. The framework abstracts away the database-specific syntax, making migrations both portable and adaptable to different database systems.

Unlock the full potential of Laravel migrations with our ultimate resource.

Experience the power of Laravel Migrations on Cloudways, streamline your development workflow with ease.

Why Would You Use Laravel Migrations?

Laravel Migrations offer a wealth of benefits that make them a must-have tool for web developers working with the Laravel PHP framework. Let’s explore some of the key reasons why you would choose to use Laravel Migrations in your web development projects.

Aspect Explanation
Database Schema Management Laravel Migrations help manage and version-control database schemas, allowing for structured and organized changes to the database structure over time.
Version Control Migrations are tracked in version control systems like Git, ensuring that changes to the database can be easily reviewed, rolled back, or applied across development environments.
Database Portability Laravel provides a database-agnostic approach, allowing you to write schema changes once and easily switch between different database systems, such as MySQL, PostgreSQL, SQLite, or SQL Server.
Rollback and Recovery Migrations offer tools for rolling back or resetting database changes, enabling developers to recover from errors, adjust the schema, and maintain a stable database state.
Documentation Migrations serve as documentation for the database schema evolution, with each migration file containing a timestamp and a description of the changes made, improving codebase transparency and maintainability.
History and Rollback Control Laravel keeps track of executed migrations and offers rollback limitations, ensuring that migrations are idempotent and controlled in their application and rollback.
Seamless Integration with Testing This integration allows developers to create test databases with the same schema as the application’s main database, making it easier to write and execute database-related tests
Codebase Consistency By encapsulating database changes in migration files, you ensure that every developer working on the project can apply these changes uniformly across different environments, from local development setups to production servers.
Dependency Management Dependency management feature simplifies the process of managing complex database changes that rely on the existence of certain structures.
Collaboration Since the database schema is defined in code, multiple developers can work on it simultaneously, and any schema changes can be easily shared and merged using version control systems like Git. This streamlines the development process and reduces conflicts.

Basic Migration Concepts

When you are beginning to construct with Laravel, you must understand migrations. Migrations are a way of versioning your database schema. They enable you to modify your database schema in a stable and controlled manner.

You make a new migration by running the make:migration command in the terminal. If you had to make a migration to add a new table named products, for instance, you would run:

php artisan make:migration create_products_table


This will generate a new migration file in your project’s database/migrations directory.

Migration Structure

A migration file normally contains two methods: up and down. The up method is applied in order to modify your database schema, and the down method is used to revert the modifications. This is an example of what a migration file could look like:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateProductsTable extends Migration
{
    public function up()
Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('description');
$table->timestamps();
        });
    }

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

Here, the up method makes a table by the name of products, and the down method drops it.

Common Migration Commands

After you have made your migration, you can execute it with the following commands:

  • php artisan migrate: It executes all pending migrations.
  • php artisan migrate:rollback: It undoes the last executed migration.
  • php artisan migrate:reset: It undoes all the migrations.
  • php artisan migrate:refresh: It undoes all the migrations and then re-executes them.

These commands are important in maintaining your database schema changes.

Data Types and Constraints

In Laravel, it comes with a variety of data types and constraints. You can use these data types and constraints in your migrations to define the structure of your database tables quite easily.

Column Data Types

Here are some of the most commonly used data types:

  • $table->id(): This is for an auto-incrementing primary key.
  • $table->string(‘column_name’): This reflects a string column with a maximum length of 255 characters.
  • $table->integer(‘column_name’): This represent an integer column.
  • $table->timestamps(): This data type will automatically add created_at and updated_at timestamp columns.
  • $table->foreignId(‘column_name’): This is to reflect a foreign key column that references the id column of another table.

Constraints

Constraints help ensure data integrity by enforcing rules on the data stored in your tables:

  • Primary Key: $table->primary(‘column_name’)
  • Foreign Key: $table->foreign(‘column_name’)->references(‘id’)->on(‘other_table’)
  • Unique Constraint: $table->unique(‘column_name’)
  • Index: $table->index(‘column_name’)

Here’s an example that uses some of these data types and constraints:

Schema::create('orders', function (Blueprint $table) {
    $table->id();
    $table->foreignId('customer_id')->constrained();
    $table->string('order_number')->unique();
    $table->timestamps();
});

In the above code block, the example is for customer_id. It is a foreign key referencing the id column of the customers table, and order_number is a unique string.

How to Implement Laravel Migration?

Creating a migration in Laravel is fundamental in managing your database schema changes. Let’s go through the process of creating a simple migration to better understand its structure.

Step 1: Create a Migration

In Laravel, you can create a migration using the make:migration Artisan command. Open your terminal and navigate to your Laravel project directory. Then, run the following command:

php artisan make:migration create_example_table

This command will create a new migration file in the database/migrations directory with a name like 2023_09_18_000000_create_example_table.php. The timestamp in the filename ensures that migrations are executed in the order they were created.

Step 2: Define the Schema

Open the newly created migration file using a code editor or the command-line text editor of your choice. You’ll find two methods in the migration file: up and down. The up method defines the changes you want to make to your database schema, while the down method specifies how to reverse those changes.

Here’s an example of a simple migration that creates a table called example with two columns:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateExampleTable extends Migration
{
public function up()
{
Schema::create('example', function (Blueprint $table) {
$table->id(); // Auto-incremental primary key
$table->string('name'); // A string column
$table->text('description')->nullable(); // A text column (nullable)
$table->timestamps(); // Created_at and updated_at timestamps
});
}
public function down()
{
Schema::dropIfExists('example');
}
}

Step 3 : Adding Columns in Table

Run the following command to create a new migration file that adds a new_column to the example table:

php artisan make:migration add_new_column_to_example_table --table=example

Updating the Migration File:

Open the newly created migration file (e.g., 2023_09_18_123456_add_new_column_to_example_table.php) and modify the up and down methods as follows:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddNewColumnToExampleTable extends Migration
{
public function up()
{
Schema::table('example', function (Blueprint $table) {
$table->string('new_column')->nullable(); // Adding a new column
});
}
public function down()
{
Schema::table('example', function (Blueprint $table) {
$table->dropColumn('new_column'); // Dropping the added column
});
}
}

Step 4: Running the Migration

To apply the migration and create the example table in your database, run the following Artisan command:

php artisan migrate

This command executes all pending migrations. Laravel keeps track of which migrations have already been run in the migrations table of your database.

Supercharge your Laravel migrations with Cloudways hosting

Experience hassle-free hosting for your Laravel migrations and unleash the full potential of your web projects

Seeders and Migrations

Seeders are a mechanism for seeding your database with the first data. Seeders tend to be paired with migrations in order to initialize your database in the proper manner initially. To generate a seeder, you use the make:seeder command as shown below:

php artisan make:seeder UsersTableSeeder

This will create a fresh seeder file inside the database/seeders directory.

Example Seeder

Here’s an example of a basic seeder that fills the users table with some seed data:

use Illuminate\Database\Seeder;
use App\Models\User;
class UsersTableSeeder extends Seeder
{
    public function run()
    {
        User::create([
            'name' => 'John Doe',
            'email' => '[email protected]',
'password' => bcrypt('password'),
        ]);

        User::create([
            'name' => 'Jane Doe',
            'email' => '[email protected]',
'password' => bcrypt('password'),
        ]));
    }

Running Seeders

Now you can easily run a seeder by just adding it to your DatabaseSeeder class. It will serves as the point of entry for running seeders:

use Illuminate\Database\Seeder;
use App\Models\User;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
$this->call([
            UsersTableSeeder::class,
        ]);
}

}

You can then execute the seeder via the following command:

php artisan db:seed


Seeders provide an easy method of seeding your database with data, particularly for development or for initializing a new project.

Error Handling and Troubleshooting

While migrating, you can get errors. Some of them are given below, along with troubleshooting solutions on what to do:

Common Errors

  • SQLSTATE[42S01]: Base table or view already exists.

Cause: Trying to create a table which already exists.
Solution: Ensure your migration files do not have the unintended creation of the same table twice. You should before creating the table run Schema::dropIfExists(‘table_name’).

  • SQLSTATE[42S02]: Base table or view not found:

Cause: Trying to change or drop a non-existent table.
Solution: Ensure the table exists before trying to change or drop it. Check your migration order and ensure the table is created first before it is referenced.

  • SQLSTATE[23000]: Integrity constraint violation:

Cause: Trying to insert data that violates a constraint (e.g., inserting a duplicate value in a unique column).
Solution: Validate your data to make sure it meets the constraints specified in your migrations.

Error Handling Strategies

  • Backup Your Database: Never forget to back up your database prior to running migrations, most importantly in production.
  • Test Migrations: Test your migrations in a staging or development environment prior to applying in production.
  • Rollback and Refresh: In case of an error, employ migrate:rollback to roll back changes and later migrate:refresh to apply all migrations.

By adopting these strategies, it is possible to minimize the risk of errors and attain seamless database schema management.

Other Migration Commands

Modifying database indexes, including adding, renaming, or removing them, can be done using Laravel migrations. Let’s walk through the process for each of these actions.

Adding To Index

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('users', function (Blueprint $table) {
$table->index('email');
});

Renaming Index

For renaming an index you can use renameIndex() for e.g.,

$table->renameIndex('email', 'mobile_no');

Removing Index

For dropping an index you can use dropIndex() for e.g.,

$table->dropIndex('email');

Using Foreign Key Constraints

Laravel can help you create foreign key constraints, which ensure that the data in your database stays consistent and follows the relationships between different tables.

$table->foreignId('id')
constrained('users')
cascadeOnUpdate()
cascadeOnDelete();

Conclusion

In conclusion, Laravel Migration simplifies database management in Laravel applications. It offers version control, database portability, collaboration support, rollback capabilities, and improved consistency and documentation.

These benefits collectively enhance the development process, making it more efficient and reliable while also contributing to the maintainability of Laravel projects.

In this blog we’ve covered the fundamentals and advanced aspects of using migrations to create, manage and modifying your database schema effectively.

If you have any questions, feel free to ask in the comments.

Q) What are migrations in Laravel?

A) Laravel migrations are version-controlled files that define database schema changes. They help developers create, modify, and share database structures across multiple environments without manually altering tables. Migrations ensure consistency and make database management more efficient.

Q) Is migration necessary in Laravel?

A) While migrations aren’t mandatory in Laravel, they are highly recommended. They streamline database schema management, making it easier to track changes, collaborate with teams, and maintain version control without manual edits.

Q) How to migrate files in Laravel?

A) In Laravel, you can migrate database files by running the command:

php artisan migrate

This applies all pending migrations and updates the database schema based on your migration files. Ensure your database is configured correctly in the .env file before running the command.

Q) Why should I use Laravel Migrations?

A) Laravel Migrations simplify database management by providing version control, ensuring consistency across environments, and allowing seamless schema modifications. They enable database agnosticism, making it easier to switch between different database systems. Additionally, migrations help teams collaborate efficiently by tracking structural changes and maintaining a clear evolution of the database schema.

Q) Can I roll back Laravel migrations?

A) Yes, you can roll back Laravel migrations using the command:

php artisan migrate:rollback

This undoes the last batch of migrations, allowing you to revert recent changes to the database schema. If needed, you can specify the number of steps to roll back using the –step option.

Q) Is it possible to run Laravel migrations in a testing environment?

A) Yes, you can run Laravel migrations in a testing environment using:

php artisan migrate --env=testing

Laravel’s testing environment uses an in-memory SQLite database by default, but you can configure it to match your application’s database settings in the phpunit.xml file.

Q) What is the best practice for Laravel migration?

A) Best practices for Laravel migrations include keeping migration files organized, using descriptive table and column names, writing reversible migrations, and avoiding data modifications inside migration files. Always test migrations in a staging environment before deploying to production.

Q) What is the benefit of migration in Laravel?

A) Laravel migrations simplify database management by allowing version control, consistency across environments, easy schema modifications, and seamless collaboration between developers. They help maintain a structured and scalable database.

Q) How to migrate a Laravel site?

A) To migrate a Laravel site, first, configure your database connection in the .env file. Then, run php artisan migrate to apply the migrations. If you need to populate the database with seed data, use php artisan migrate –seed. If you want to refresh all migrations and start fresh, php artisan migrate:refresh will roll back and re-run all migrations.

Q) Can I modify existing columns in Laravel migrations?

Yes, you can modify existing columns in Laravel migrations using the table method’s change function. Here’s an example of how you can do it:

public function up()
{
    Schema::table('your_table_name', function (Blueprint $table) {
        $table->string('new_column_name')->change();
    });
}

Share your opinion in the comment section. COMMENT NOW

Share This Article

Salwa Mujtaba

Salwa Mujtaba is a Technical Content Writer at Cloudways. With a strong background in Computer Science and prior experience as a team lead in Cloudways Operations, she brings a deep understanding of the Cloudways Platform to her writing. Salwa creates content that simplifies complex concepts, making them accessible and engaging for readers. When she's not writing, you can find her enjoying good music, reading a book, or spending quality time with her family.

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour