TechnicalEasy PHP & Laravel
What are migrations in Laravel and why are they useful?
Asked for Backend Developer, Full-Stack Developer
Why they ask this: Every team project uses migrations; this checks you can work safely with a shared database schema.
Answer
Migrations are version control for the database schema. Each migration is a PHP class with an up() method that makes a change and a down() method that reverses it.
php
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->foreignId('company_id')->constrained()->cascadeOnDelete();
$table->string('title');
$table->unsignedInteger('salary_min')->nullable();
$table->timestamps();
});Useful commands: php artisan make:migration, migrate, migrate:rollback, migrate:status.
Why they are useful:
- Every developer and server gets the same schema by running
php artisan migrate. - Changes are reviewed in Git like any other code.
- Changes can be rolled back.
Never edit a migration that has already run in production. Create a new one instead.
Can you explain this in your own words?