
Migration Structure in Laravel
The laravel database migrations are used to create, modify, and delete database tables and columns in a structured and incremental manner. Migrations are typically stored in the database/migrations
directory and follow a specific structure defined by Laravel. Here’s an overview of the migration structure in Laravel:
1. Migration Class:
Each migration is represented by a PHP class. The class name is typically generated based on a timestamp to ensure that migrations are executed in the order they were created. For example, a migration class for creating a “posts” table might be named something like 2023_09_15_000000_create_posts_table.php
. The timestamp ensures that migrations are executed in the order they were created.
Here’s an example of a basic migration class structure:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
public function up()
{
// Code to create the "posts" table
}
public function down()
{
// Code to drop the "posts" table
}
}
2. up
Method:
The up
method is responsible for defining the changes you want to make to the database schema. Inside this method, you use the Schema builder provided by Laravel to create tables, define columns, set constraints, and so on. For example, to create a “posts” table:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
3. down
Method:
The down
method is responsible for defining how to reverse the changes made by the up
method. This method is used when rolling back migrations or undoing a specific migration. For example, to drop the “posts” table:
public function down()
{
Schema::dropIfExists('posts');
}
4. Running Migrations:
To execute the migrations and apply the schema changes to the database, you use the migrate
Artisan command:
php artisan migrate
This command runs all pending migrations in the order they were created.
5. Rolling Back Migrations:
If you need to undo a migration, you can use the migrate:rollback
Artisan command. This command executes the down
method of the last batch of migrations:
php artisan migrate:rollback
You can also specify the --step
option to rollback a specific number of batches:
php artisan migrate:rollback --step=2
These are the fundamental components and structure of migrations in Laravel. Migrations provide a structured and version-controlled way to manage your database schema, making it easier to work collaboratively and keep your database schema in sync with your application’s code.