laravel-migraciones-de-base-de-datos-en-laravel

Database Migrations in Laravel

  • 3 min

An migration is a versioned description of a change to the database structure.

Migrations are like version control for your database. They allow your team to define and share the database structure (tables and columns) using PHP code instead of SQL.

Why use migrations?

Imagine you are working locally and you create the productos table.

  • Without migrations: You have to remember to also create it on the production server and pass the SQL to your teammates. If you forget a column, the website breaks.
  • With migrations: You upload your code. Your teammate (or the server) runs a command (php artisan migrate) and Laravel creates the tables or adds the necessary columns automatically. Everyone always has the same database.

Creating a migration

Let’s ask our Artisan assistant to create the file to define a products table.

php artisan make:migration create_productos_table
Copied!

This generates a file in database/migrations with a timestamp (e.g., 2023_10_25_000000_create_productos_table.php). The date is important: it allows Laravel to know the order in which to execute the changes.

Anatomy of a migration (up and down)

When you open the file, you will see two fundamental methods. You just need to fill them with what you want to happen.

  • up(): What happens when moving forward. Here you create tables or add columns.
  • down(): What happens when moving backward (undoing). Here you delete what you created in up().

Example: defining the productos table

Laravel uses a Blueprint object to define data types in an agnostic way (it doesn’t matter if you use MySQL, PostgreSQL, or SQLite, the code is the same).

public function up()
{
    Schema::create('productos', function (Blueprint $table) {
        // Auto-incrementing ID (Primary Key)
        $table->id(); 
        
        // VARCHAR(255)
        $table->string('nombre'); 
        
        // TEXT (for long texts), nullable allows it to be empty
        $table->text('descripcion')->nullable(); 
        
        // DECIMAL(8, 2) for monetary values
        $table->decimal('precio', 8, 2); 
        
        // BOOLEAN (with default value false)
        $table->boolean('activo')->default(true);
        
        // Automagically creates two columns: 'created_at' and 'updated_at'
        $table->timestamps(); 
    });
}

public function down()
{
    // If we undo the migration, we drop the table
    Schema::dropIfExists('productos');
}
Copied!

Running the migration

So far we have only written code. The database is still empty. To apply the changes, we run:

php artisan migrate
Copied!

Laravel will read all the migrations that have not been executed yet, translate them into SQL, and run them against the database. You will see green success messages.

If you go to your database manager, you will see the productos table perfectly created!

Time travel: rollback

Did you make a mistake creating the table? Did you put the wrong name? Don’t go into phpMyAdmin to delete it. Use the undo command:

php artisan migrate:rollback
Copied!

This executes the down() method of the last migration (deletes the productos table). Then you can fix the PHP file and run migrate again.

Modifying existing tables

What happens if the table already exists and you want to add a new column, for example stock? Do not edit the previous migration (because that one was already executed). Create a new one:

  1. php artisan make:migration add_stock_to_productos_table
  2. In the up(): $table->integer('stock');
  3. In the down(): $table->dropColumn('stock');
  4. php artisan migrate.

Laravel detects that there is only one new file and executes only that change.