Laravel Migrations: Create, Run, and Manage With This Guide

Laravel migrations

January 24, 2025

Want to know how to manage Laravel database schema changes seamlessly? Let’s read these Laravel migrations in-depth guide and get all your answers!

We will start with the basics in order to fully understand what they are, what they do, prerequisites, and ways to implement them. Laravel database migration is a powerful feature for managing database schemas in your web applications.

It is also one of the most important concepts to understand when you have to make a scalable website with Laravel. That being said, they also act as a version control system for your database migrations that allow developers to create, modify, and share database structures across different environments.

It saves you from the hassle of writing raw SQL and you can simply rely on Laravel’s intuitive syntax to define tables, columns, and relationships.

Let’s discuss the essentials in detail below.

What are Laravel Migrations?

It is a set of instructions that enable you to make changes in the database schema in Laravel applications. By using Laravel migrations, developers leverage an organized approach to synchronize your database with your application’s codebase across various types of environments.

You can perform migrations without having to worry about the specific database system you’re using, whether it’s MySQL, PostgreSQL, SQLite, or others supported by Laravel. By performing Laravel database migrations, you can create new tables, modify or alter existing tables, add columns, and seed the database with initial data.

As your Laravel web application continues to update and evolve with time (no wonder it has become one of the top PHP frameworks), it will require changes in the database such as the addition of new tables or new data types. By performing Laravel migrations, the need for manual setup is eliminated and the chances of errors significantly reduce. By working on this process, you get a clear history of changes executed in the order along with a timestamp. It simplifies tasks like rolling back to previous states or applying the changes incrementally.

What are the prerequisites for Laravel Migrations?

To follow this tutorial, there are certain prerequisites that have been followed in the tutorial. Therefore, make sure you also have the requirements completed for seamless Laravel database migrations.

Laravel Installed

Ensure you have a Laravel project set up. If not, you can create one using:

composer create-project --prefer-dist laravel/laravel project-name

Database Connection

Configure your database settings in the .env file of your Laravel project. Example for MySQL:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password

Database Driver

Ensure you have the appropriate database driver installed. For example, if you’re using MySQL, the PHP extension pdo_mysql must be enabled. For PostgreSQL, enable pdo_pgsql.

Basic Knowledge of Artisan Commands

Familiarity with Laravel Artisan commands is important, as migrations heavily rely on them. For example:

  • php artisan make:migration to create a migration file.

artisan commands in laravel migration

  • php artisan migrate to run migrations.

php artisan migrate

A file is created automatically in which there are three classes include i.e., migration, blueprint, and schema.

laravel migrations

Understanding of Database Basics

Before you start following the Laravel migrations process make sure you have a fundamental understanding of database concepts like tables, columns, data types, and constraints will help you define schemas effectively in migration files.

PHP Environment

Ensure you have PHP installed (recommended version 8.0 or higher) with a local server setup like XAMPP, WAMP, or Laravel Homestead.

Composer Installed

Laravel relies on Composer for dependency management, so make sure Composer is installed and functional on your system.

Code Editor

You need a code editor like Visual Studio Code, PhpStorm, or Sublime Text to write and manage migration files, as they are PHP scripts.

Here is a tip: This is a fundamental tool for any Laravel development, not just migrations.

How to Create and Implement Laravel Migration?

In order to create and implement Laravel migration, there are four important steps that include:

  • Create Database
  • Create Database Migration
  • Seeding
  • Create Model

Create Database

When creating there are two commands; you can either use a manual command such as CREATE DATABASE laravel-db or use a software such as Xampp (Phpmyadmin). Once the database is created, you need to specify which database will be used in your project. For this, access the .env file in your root folder. For example, here we have given the name laravel-db and we can access it in root folder. You will also find variables with prefix db that are used in the coding.

database in laravel migration

We have three variables here as shown below which have their defined value.

database laravel migration

In order to use these variables, from the left menu access the folder config and open it.

You will see the complete information against each database and variables that you can change as per your requirements. We will be using MySQL in this tutorial so let’s get started.

use mysql in laravel migration

Once this is set, the next step is to create database migrations. So, let’s see how you can do that.

Create Database Migrations

This step states creating tables in the database by using the automation feature. Migrations in Laravel are PHP classes used to define and modify database tables. To create a new migration file, you use the Artisan command:

php artisan make:migration create_students_table0

create table in laravel migration

This generates a new file in the database/migrations folder. The file’s name will include a timestamp to ensure migrations run in the correct order. The name you provide (create_students_table) should describe the purpose of the migration. You can also use additional flags like –table to target an existing table or –create to create a new one. For instance:

php artisan make:migration add_status_to_students_table --table=students

This would create a migration for modifying the students table to include a status column.

Defining the Schema

Once the migration file is created, you’ll see two methods: up() and down().

  • The up() Method: This is where you define the changes you want to make to the database. For example, creating a table or adding a new column. The Schema facade provides methods for defining columns, primary keys, foreign keys, and constraints.

Below is an example of it and you can also refer to the screenshot:

public function up() {
    Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamps();
    });
}
  • The down() Method: This method reverses the changes made in up(). It’s essential for rolling back migrations. For instance, if you create a table in up(), you should drop it in down():
public function down() {
Schema::dropIfExists('students);
}

schema in laravel migration

Both methods ensure migrations are reversible and maintain consistency across environments.

Want to understand the Laravel variables?

Running Migrations

To apply the migrations and update the database, use the following Artisan command:

php artisan migrate

This will execute all the migrations that haven’t been run yet. Laravel uses a migrations table to track which migrations have been applied. If there’s an issue, you’ll receive an error message, helping you debug the problem.

Ensure your database connection is correctly configured in the .env file before running migrations.

Rolling Back Migrations

If you need to undo changes made by the last batch of migrations, use:

php artisan migrate:rollback

This command will call the down() method for each migration in the last batch. Rolling back is helpful during development when testing changes. If you need to reset all migrations and reapply them, use:

php artisan migrate:refresh

This drops all tables and re-runs all migrations from the start.

Modifying Existing Tables

Sometimes, you need to update an existing table to add, modify, or remove columns. To do this, generate a migration targeting the specific table:

php artisan make:migration add_status_to_students_table --table=students

modify existing table laravel migration

In the up() method, define the modification:

public function up() {
Schema::table('students', function (Blueprint $table) {
$table->string('status')->nullable();
});
}

code in laravel migration

In the down() method, ensure the change can be reversed

public function down() {
Schema::table('students', function (Blueprint $table) {
$table->dropColumn('status');
});
}

Using this approach ensures you can maintain version control over database changes.

Seeding the Database

Seeding is the process of populating the database with sample data. To create a seeder file, run:

php artisan make:seeder StudentsTableSeeder

In the generated file, define the data you want to insert:

public function run() {
DB::table('students)->insert([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password'),
]);
}

Run the seeder using:

php artisan db:seed --class=StudentsTableSeeder

You can also call multiple seeders from DatabaseSeeder.php to seed multiple tables in one command.

Running Migrations

Once you’ve defined the schema in your migration files, the next step is to apply these changes to the database. This is done using the php artisan migrate command:

php artisan migrate

How It Works:

  1. Laravel will check the migrations table in your database to see which migrations have already been run.
  2. It will execute the up() method of any migration files that haven’t been applied yet.
  3. This updates your database schema by creating or modifying tables as defined in your migrations.

When you run the migration command, you might see output like this:

makefile
Migrating: 2025_01_20_123456_create_students_table
Migrated: 2025_01_20_123456_create_students_table (45ms)

run laravel migration

Troubleshooting:

  • Database Connection Issues: Ensure your .env file contains the correct database credentials (DB_HOST, DB_DATABASE, DB_USERNAME, and DB_PASSWORD).
  • Pending Migrations: If migrations are stuck, check the migrations table in your database for incomplete or failed entries.

This step is crucial for updating your database to reflect the structure defined in your migration files.

Make it Easier by Hiring Laravel Developers

Pro tip: Always ensure you’ve saved your migration files before running this command!

Refreshing Migrations

Refreshing migrations is a quick way to reset and reapply all migrations. This is useful for testing a clean slate or integrating changes from other developers. The command:

php artisan migrate:refresh

Drops all tables and re-runs all migrations. You can also use:

php artisan migrate:refresh --seed

This will re-run migrations and seed the database in one step, saving time during development.

Other Migration Commands Used in Laravel

There are other important migration commands that are used in Laravel. Developers use these commands to make the process easier and smooth. To name, these important migration commands include Rollback Migrations, Refresh Migrations, Fresh Migrations, and others.

Check Migration Status

php artisan migrate:status

This command shows a list of all your migration files and their current status, making it easy to track which migrations have been applied and which haven’t. It’s helpful when debugging or reviewing the migration history.

Rollback Migrations

php artisan migrate:rollback

When you need to undo the last batch of migrations, this command comes in handy. It’s particularly useful during development when testing database changes or fixing an error in the latest migration.

Reset All Migrations

php artisan migrate:reset

This command undoes all the migrations applied to your database, essentially wiping it clean. Use it cautiously, especially in production environments, as it drops all tables and clears your database schema.

Refresh Migrations

php artisan migrate:refresh

Need to reset your database and apply all migrations again? This command does exactly that. It’s a great way to start fresh while keeping your schema definitions intact. You can also include the –seed flag to repopulate your tables with test data after refreshing.

Fresh Migrations

php artisan migrate:fresh

This command is similar to refresh but even simpler. It drops all the tables and applies migrations from scratch. It’s perfect for starting over without retaining any data or schema history.

Conclusion

Laravel database migration is an essential step and tool in order to manage your database scheme effectively. It not only saves your time through automation but also reduces errors. By using the process, you can streamline the process of creating, modifying, and rolling back database tables but also ensure consistency across development environments. By leveraging commands like migrate:status, rollback, and refresh, you can handle schema changes with confidence and precision.

So, if you are working on a new project or maintaining an existing one, understanding and using Laravel migrations will save you time and reduce errors. With the right approach, you can keep your database structure organized, scalable, and adaptable to future needs.

Hire Laravel Developers

Want a seamless Laravel migration? At Devace, we provide skilled Laravel developers to perform migrations with minimal downtime and security so that you don’t have to worry about manual errors that might come. With over 10 years of experience, our developers have hands-on experience and technical knowledge and have completed more than a hundred projects. We bring you expertise in Laravel that is second to none. So what are you waiting for?

Book a call with us and get started on your project.

Frequently Asked Questions

How to make a new migration in Laravel?

Creating a new migration in Laravel involves some of the steps. These steps include following the above steps that we have mentioned i the blog post. However, you can use the following command:

php artisan make:migration migration_name

Also, simply do one step that is replace migration_name with a descriptive name, such as create_users_table. This creates a new migration file in the database/migrations directory, where you can define the schema changes.

Is migration necessary in Laravel?

If not necessary, they are highly recommended. Why? Because migrations allow you to version-control your database schema, ensure consistency across environments, and easily apply or revert changes. This is especially useful in team settings or during continuous integration.

Is it possible to migrate PHP to Laravel?

Yes, it is completely possible to migrate PHP to Laravel. All you will need to do is to manually integrate your application’s functionality into Laravel’s structure, such as converting routes, controllers, and database queries to follow Laravel’s conventions and best practices. Or, you can simply hire the best Laravel developer from us.

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

Yes, Laravel supports running migrations in a testing environment. By setting up a separate test database in your .env.testing file, you can use the php artisan migrate command to prepare the test database without affecting your main database.

How to refresh a migration in Laravel?

To refresh migrations, use the command:

php artisan migrate:refresh

This resets all migrations and re-applies them. If needed, you can add the –seed flag to repopulate your database with test data after refreshing.

How to roll back migration to Laravel?

In order to roll back migrations, use the command:

php artisan migrate:rollback

This undoes the last batch of migrations. Use –step=n to specify how many batches to roll back. It’s useful for testing or fixing migration issues.

Table of Contents
Talk to our experts in this domain