Adding a new table with a new migration - McNamara84/ladis GitHub Wiki
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
php artisan make:migration create_materials_table
This creates a new file in database/migrations/
with a template.
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');
}
};
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();
});
}
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();
- Allows
-
->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();
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
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()
.
$table->index('parent_id', 'fk_material_material1_idx');
- 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
Write down error messages and their solutions here