Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Migrations

A migration is a file that describes a database change in code: create a table, add a column. Migrations are stored in the project together with the code, so every developer and the server have the same database structure.

Connecting to the database

Connection settings go into the .env file in the project root:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=secret

Creating a migration

php artisan make:migration create_posts_table

The file appears in the database/migrations folder. The date in its name sets the order of execution.

Describing a table

The up() method describes the change, and the down() method describes how to undo it:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }
 
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

Column types

MethodWhat it creates
id()An auto-incrementing primary key
string('name')A short string (up to 255 characters)
text('body')Long text
integer('views')An integer
boolean('is_published')A boolean value
timestamps()The created_at and updated_at columns

Modifiers refine a column: ->nullable() allows an empty value, ->default(0) sets a default, ->unique() forbids duplicates.

Running

php artisan migrate

Laravel runs only the migrations that have not been run yet. The last batch is undone with php artisan migrate:rollback.

Changing a table

To add a column to an existing table, create a new migration and use Schema::table():

public function up(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->integer('views')->default(0);
    });
}
 
public function down(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->dropColumn('views');
    });
}

Common mistake

Do not edit a migration that has already run: Laravel considers it applied and will not run it again, so your teammates' and the server's databases stay as they were. Create a new migration for every change.

Thanks for reading!

Donate to the site — we work hard for you.