Adding a new table with a new migration - McNamara84/ladis GitHub Wiki

Step 1: Create a new migration file

Open your terminal and navigate to our project root directory where you clone the repository. Run:

php artisan make:migration create_TABLENAME_table

Naming convention for TABALENAME: plural, lowercase

Example

php artisan make:migration create_materials_table

This creates a new file in database/migrations/ with a template.

Step 2: Open the migration file

Navigate to database/migrations/ and open the newly created file. You'll see:

<?php

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('TABLE_NAME', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('TABLE_NAME');
    }
};

Step 3: Define your table structure

Tip

You can find all possible data types in Laravel here.

Add columns between $table->id(); and $table->timestamps();:

public function up(): void
{
    Schema::create('TABLE_NAME', function (Blueprint $table) {
        $table->id();
        // Add your columns here
        $table->string('BEISPIELNAME'); // This is an example for a column with datatype string
        $table->timestamps();
    });
}

Step 4: Set column modifiers where needed

Tip

You can find all possible column modifiers in Laravel here.

Add these after the column type:

  • ->nullable()
    • Allows NULL values.
    • Example: $table->text('description')->nullable();
  • ->default($value)
    • Sets the default value.
    • Example: $table->integer('status')->default(1);
  • ->unique()
    • Adds unique constraint.
    • Example: $table->char('postal_code', 5)->unique();
  • ->unsigned()
    • Allows only positive numbers.
    • Example: $table->integer('age')->unsigned();

Step 5: Adding foreign keys if needed (1:1, 1:n)

For relationships between tables you can specify a column as a foreign key:

$table->foreignId('federal_state_id')->constrained('federal_states') // Minimum
      ->onDelete('cascade') // If needed
      ->onUpdate('cascade'); // If needed

Step 6: Adding indexes if needed

Tip

More Informations on indexes you can find here.

For better query performance we have mentioned some columns to have an index. You can add an index with index().

Example

$table->index('parent_id', 'fk_material_material1_idx');

Step 7: Run the migration

  • Execute the migration to create the table:
    • php artisan migrate
  • Rollback the last migration if something does not work:
    • php artisan migrate:rollback
  • Rollback all migrations if something really strange does not work:
    • php artisan migrate:reset

Troubleshooting

Write down error messages and their solutions here

References

⚠️ **GitHub.com Fallback** ⚠️