In Laravel, migrations are a feature that allows you to manage your database schema and perform database operations in a version-controlled manner. Migrations are written in PHP and are stored in the database/migrations
directory of your Laravel project.
You can create a new migration using the php artisan make:migration
Artisan command. For example, to create a migration for creating a new table, you would run:
php artisan make:migration create_users_table
This command will create a new migration file in the database/migrations
directory with a timestamp prefix and the provided name.
Once you have created a migration file, you can open it and define the database schema changes you want to make using Laravel's Schema Builder. For example, to create a users
table, you can define the table schema in the up
method:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
In the down
method, you define how to reverse the changes made by the migration. In this case, it drops the users
table.
To run all pending migrations, you can use the migrate
Artisan command:
php artisan migrate
This will execute all the migrations that haven't been run yet.
To roll back the last migration operation, you can use the migrate:rollback
Artisan command:
php artisan migrate:rollback
This will revert the last migration that was run.
Note - Laravel migrations provide a powerful and convenient way to manage your database schema. By using migrations, you can easily version control your database changes, ensure consistency across environments, and easily roll back changes if needed.