Hey there! If you're working with Laravel 12, migrations are an essential part of managing your database structure. Instead of manually creating and modifying tables, Laravel provides an easy way to handle database changes using migration files.
In this guide, I'll show you how to create, run, and rollback migrations step by step.
Steps to Create, Run, and Rollback Migrations in Laravel 12
To create a new migration file, use the following Artisan command:
php artisan make:migration create_users_table
This will generate a migration file inside the database/migrations directory. The file name will look something like:
Open the generated migration file:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
};
After defining the table schema, run the migration to create the table in your database:
php artisan migrate
This will execute all pending migrations and create the necessary tables in your database.
If you need to modify an existing table, create a new migration:
php artisan make:migration add_phone_to_users_table --table=users
Then, update the up
method to add the new column:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('phone')->nullable();
});
}
Run the migration again:
php artisan migrate
If you made a mistake or need to revert changes, you can rollback the last migration using:
php artisan migrate:rollback
This will undo the last batch of migrations.
To rollback all migrations and reset the database, run:
php artisan migrate:reset
Then, re-run all migrations:
php artisan migrate
If you want to completely refresh your database by rolling back and re-running all migrations, use:
php artisan migrate:refresh
To refresh the database and seed it with test data:
php artisan migrate:refresh --seed
You might also like: