Migrations provide a way to manage database schema changes in your application. They allow you to create, modify, and delete database tables and columns.
Laravel's migration system is powered by the Artisan command-line tool, making it easy to create, run, and roll back migrations.
Basic Step to create Migration
1. Create a Migration
Use the Artisan command to generate a new migration file. The file will be created in the database/migrations directory.
php artisan make:migration create_table_name
This will generate a migration file with a name like
2022_01_01_000000_create_table_name.php.
2. Define the Schema Changes
Open the generated migration file and define the schema changes in the up method.
Use Laravel's Schema Builder to create tables, define columns, indexes, and other aspects of the database schema.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTableName extends Migration
{
public function up()
{
Schema::create('table_name', function (Blueprint $table) {
$table->id();
$table->string('column_name');
// Add other columns as needed
$table->timestamps(); // Adds created_at and updated_at columns
});
}
public function down()
{
Schema::dropIfExists('table_name');
}
}
?>
3.Run the Migration:
Use the Artisan command to execute the migrations and apply the changes to the database.
php artisan migrate
4.Rollback Migrations
If needed, you can roll back the last batch of migrations using the following command:
php artisan migrate:rollback
5.View Migration Status
To view the status of migrations, including which ones have been run and which are pending, you can use:
php artisan migrate:status
These basic steps cover the process of creating and running migrations in Laravel.