In this guide, we'll see how to create, run, and roll back migration in laravel 11. Migrations are like version control for your database. Also, see run specific migration in laravel 11 and roll back specific migration in laravel 11.
A migration class contains two methods: up
and down
. The up
method is used to add new tables, columns, or indexes to your database, while the down
method should reverse the operations performed by the up
method.
First, we'll create a migration using the following command.
php artisan make:migration create_blogs_table
After running the above command, you will see a new file in the database/migration folder.
database/migrations/2024_04_06_144031_create_blogs_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('blogs', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->boolean('is_published')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('blogs');
}
};
Then, we'll migrate the migration into the database using the following command.
php artisan migrate
Run a specific migration using the following command.
php artisan migrate --path=/database/migrations/2024_04_06_144031_create_blogs_table.php
Rollback a migration using the following command:
php artisan migrate:rollback
Roll back a specific migration using the following command.
php artisan migrate:rollback --path=database/migrations/2024_04_06_144031_create_blogs_table.php
Reset migration will roll back all the application's migrations.
php artisan migrate:reset
In addition to the column types listed above, there are several column "modifiers" you may use when adding a column to a database table.
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('users', function (Blueprint $table) {
$table->string('email')->nullable();
});
To drop a column, you may use the dropColumn
method on the schema builder:
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('votes');
});
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['votes', 'avatar', 'location']);
});
You might also like: