BPM Migration - API Reference
← Kembali ke Overview | Changelog
Referensi lengkap untuk semua class, method, dan trait di BPM Migration library
Versi: 0.4.1
Daftar Isi
Classes
- BpmSchema - Schema wrapper dengan Model support
- Migration - Base migration class
- BpmBlueprint - Custom Blueprint dengan helper methods
Traits
- HasCreator - Auto-fill creator_id pada create
- HasEditor - Auto-fill latest_editor_id pada update
Global Macros
- constrainedFor() - ColumnDefinition macro untuk Model-aware constraint
Classes
BpmSchema
SCHEMA WRAPPER
BpmSchema menyediakan API yang sama dengan Laravel's Schema facade, tetapi menggunakan BpmBlueprint secara internal. Semua method di bawah ini adalah wrapper untuk Schema method Laravel.
FITUR - v0.3.0
BpmSchema mendukung Model instances dan class names sebagai parameter tabel, selain string. Ini memungkinkan type-safe schema operations dan integrasi yang lebih baik dengan Eloquent Models.
Namespace: Bpmlib\BpmMigration\BpmSchema
Contains:
- extend()
- create()
- table()
- drop()
- dropIfExists()
- rename()
- dropColumns()
- whenTableHasColumn()
- whenTableDoesntHaveColumn()
- hasTable()
- hasColumn()
- getColumnListing()
- getColumns()
extend()
public static function extend(?string $connection = null): BuilderMendapatkan schema builder instance dengan custom BpmBlueprint resolver.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$connection | string|null | null | Nama database connection |
Returns: Illuminate\Database\Schema\Builder - Schema builder dengan BpmBlueprint
Contoh:
use Bpmlib\BpmMigration\BpmSchema;
$schema = BpmSchema::extend();
$schema->create('products', function ($table) {
// $table adalah BpmBlueprint instance
$table->id();
$table->actor();
$table->timestamps();
});create()
public static function create(
string $table,
Closure $callback,
?string $connection = null
): voidMembuat tabel baru dalam database.
PARAMETER DESIGN
Method create() hanya menerima string sebagai nama tabel, bukan Model. Ini by design karena tabel belum ada saat pembuatan.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string | - | Nama tabel yang akan dibuat |
$callback | Closure | - | Callback untuk mendefinisikan struktur tabel |
$connection | string|null | null | Nama database connection |
Contoh:
BpmSchema::create('products', function ($table) {
$table->id();
$table->string('name');
$table->decimal('price', 10, 2);
$table->actor();
$table->timestamps();
});table()
public static function table(
string|Model $table,
Closure $callback,
?string $connection = null
): voidMemodifikasi tabel yang sudah ada.
MODEL SUPPORT - v0.3.0
Method ini menerima Model instance atau class name selain string table name.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string|Model | - | Nama tabel (string), Model instance, atau Model class name |
$callback | Closure | - | Callback untuk mendefinisikan perubahan |
$connection | string|null | null | Nama database connection |
Contoh:
use App\Models\Product;
// String table name
BpmSchema::table('products', function ($table) {
$table->string('sku')->after('id');
});
// Model class (v0.3.0+)
BpmSchema::table(Product::class, function ($table) {
$table->string('sku')->after('id');
});
// Model instance (v0.3.0+)
$product = new Product();
BpmSchema::table($product, function ($table) {
$table->string('sku')->after('id');
});drop()
public static function drop(
string|Model $table,
?string $connection = null
): voidMenghapus tabel dari database.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string|Model | - | Nama tabel (string), Model instance, atau Model class name |
$connection | string|null | null | Nama database connection |
Contoh:
use App\Models\Product;
// String
BpmSchema::drop('products');
// Model class
BpmSchema::drop(Product::class);dropIfExists()
public static function dropIfExists(
string|Model $table,
?string $connection = null
): voidMenghapus tabel jika ada.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string|Model | - | Nama tabel (string), Model instance, atau Model class name |
$connection | string|null | null | Nama database connection |
Contoh:
BpmSchema::dropIfExists('products');rename()
public static function rename(
string|Model $from,
string $to,
?string $connection = null
): voidMengganti nama tabel.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$from | string|Model | - | Nama tabel lama (string), Model instance, atau Model class name |
$to | string | - | Nama tabel baru |
$connection | string|null | null | Nama database connection |
Contoh:
use App\Models\Product;
// String to string
BpmSchema::rename('products', 'items');
// Model to string
BpmSchema::rename(Product::class, 'items');dropColumns()
public static function dropColumns(
string|Model $table,
string|array $columns,
?string $connection = null
): voidMenghapus satu atau lebih kolom dari tabel.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string|Model | - | Nama tabel (string), Model instance, atau Model class name |
$columns | string|array | - | Nama kolom atau array nama kolom |
$connection | string|null | null | Nama database connection |
Contoh:
// Single column
BpmSchema::dropColumns('products', 'description');
// Multiple columns
BpmSchema::dropColumns('products', ['description', 'notes']);whenTableHasColumn()
public static function whenTableHasColumn(
string|Model $table,
string $column,
Closure $callback,
?string $connection = null
): voidExecute callback jika tabel memiliki kolom tertentu.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string|Model | - | Nama tabel (string), Model instance, atau Model class name |
$column | string | - | Nama kolom |
$callback | Closure | - | Callback yang dijalankan jika kolom ada |
$connection | string|null | null | Nama database connection |
Contoh:
BpmSchema::whenTableHasColumn('products', 'old_column', function () {
BpmSchema::table('products', function ($table) {
$table->dropColumn('old_column');
});
});whenTableDoesntHaveColumn()
public static function whenTableDoesntHaveColumn(
string|Model $table,
string $column,
Closure $callback,
?string $connection = null
): voidExecute callback jika tabel tidak memiliki kolom tertentu.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string|Model | - | Nama tabel (string), Model instance, atau Model class name |
$column | string | - | Nama kolom |
$callback | Closure | - | Callback yang dijalankan jika kolom tidak ada |
$connection | string|null | null | Nama database connection |
Contoh:
BpmSchema::whenTableDoesntHaveColumn('products', 'sku', function () {
BpmSchema::table('products', function ($table) {
$table->string('sku')->unique();
});
});hasTable()
public static function hasTable(string|Model $table, ?string $connection = null): boolCek apakah tabel ada.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string|Model | - | Nama tabel (string), Model instance, atau Model class name |
$connection | string|null | null | Nama database connection |
Returns: bool - True jika tabel ada
Contoh:
use App\Models\Product;
if (BpmSchema::hasTable('products')) {
// Table exists
}
// Model support (v0.3.0+)
if (BpmSchema::hasTable(Product::class)) {
// Table exists
}hasColumn()
public static function hasColumn(
string|Model $table,
string $column,
?string $connection = null
): boolCek apakah tabel memiliki kolom tertentu.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string|Model | - | Nama tabel (string), Model instance, atau Model class name |
$column | string | - | Nama kolom |
$connection | string|null | null | Nama database connection |
Returns: bool - True jika kolom ada
Contoh:
if (BpmSchema::hasColumn('products', 'sku')) {
// Column exists
}getColumnListing()
public static function getColumnListing(
string|Model $table,
?string $connection = null
): arrayMendapatkan daftar nama kolom dalam tabel.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string|Model | - | Nama tabel (string), Model instance, atau Model class name |
$connection | string|null | null | Nama database connection |
Returns: array - Array berisi nama-nama kolom
Contoh:
$columns = BpmSchema::getColumnListing('products');
// ['id', 'name', 'price', 'creator_id', 'latest_editor_id', ...]getColumns()
public static function getColumns(
string|Model $table,
?string $connection = null
): arrayMendapatkan informasi lengkap tentang kolom-kolom dalam tabel.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$table | string|Model | - | Nama tabel (string), Model instance, atau Model class name |
$connection | string|null | null | Nama database connection |
Returns: array - Array berisi metadata detail kolom
Contoh:
$columns = BpmSchema::getColumns('products');
// [
// ['name' => 'id', 'type' => 'char', 'nullable' => false, ...],
// ['name' => 'name', 'type' => 'varchar', 'nullable' => false, ...],
// ...
// ]Migration
BASE CLASS
Extend class ini untuk otomatis menggunakan BpmBlueprint tanpa harus call BpmSchema secara manual.
Base migration class untuk BPM migrations. Menyediakan akses ke BpmSchema tanpa mengubah global Schema behavior.
Namespace: Bpmlib\BpmMigration\Migration
Extends: Illuminate\Database\Migrations\Migration
Contains:
schema()
protected function schema(?string $connection = null): BuilderMendapatkan schema builder instance yang menggunakan custom BpmBlueprint.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$connection | string|null | null | Nama database connection |
Returns: Illuminate\Database\Schema\Builder - Schema builder dengan custom blueprint resolver
Contoh:
use Bpmlib\BpmMigration\Migration;
class CreateProductsTable extends Migration
{
public function up(): void
{
$this->schema()->create('products', function ($table) {
$table->id();
$table->string('name');
$table->actor();
$table->timestamps();
});
}
public function down(): void
{
$this->schema()->dropIfExists('products');
}
}BpmBlueprint
PERHATIAN
Blueprint ini hanya tersedia saat menggunakan BpmSchema atau Migration class. Tidak bekerja dengan Laravel's default Schema facade.
Custom Blueprint yang extends Laravel's Blueprint dengan method tambahan untuk ULID primary keys, actor tracking, timestamps dengan soft deletes, dan foreign key helpers.
Namespace: Bpmlib\BpmMigration\Blueprint\BpmBlueprint
Extends: Illuminate\Database\Schema\Blueprint
Contains:
Primary Key Methods
id()
OVERRIDE
Overrides Laravel's default id() method untuk menggunakan ULID instead of auto-increment integer.
public function id(string $column = 'id'): ColumnDefinitionMembuat primary key column menggunakan ULID.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$column | string | 'id' | Nama kolom |
Returns: ColumnDefinition - Column definition untuk chaining
Contoh:
$table->id(); // Kolom 'id' dengan type ULID, primary key
// Equivalent dengan:
$table->ulid('id')->primary();intId()
public function intId(string $column = 'id'): ColumnDefinitionMembuat primary key column menggunakan BIGINT auto-increment (Laravel default).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$column | string | 'id' | Nama kolom |
Returns: ColumnDefinition - Column definition untuk chaining
Contoh:
// Untuk legacy systems atau saat ULID tidak sesuai
$table->intId();
// Equivalent dengan:
$table->bigIncrements('id');Actor Tracking Methods
Methods untuk membuat kolom yang track user pembuat dan editor data.
creator()
public function creator(
string $column = 'creator_id',
bool $withForeignKey = true,
?string $userTable = null
): voidMembuat kolom creator_id untuk menyimpan user pembuat data.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$column | string | 'creator_id' | Nama kolom |
$withForeignKey | bool | true | Tambahkan foreign key constraint |
$userTable | string|null | null | Nama tabel users (default: 'users') |
Contoh:
// Default: creator_id dengan FK ke users table
$table->creator();
// Custom column name
$table->creator('created_by');
// Tanpa foreign key (microservice)
$table->creator(withForeignKey: false);
// Custom users table
$table->creator(userTable: 'accounts');editor()
public function editor(
string $column = 'latest_editor_id',
bool $withForeignKey = true,
?string $userTable = null
): voidMembuat kolom latest_editor_id untuk menyimpan user terakhir edit data.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$column | string | 'latest_editor_id' | Nama kolom |
$withForeignKey | bool | true | Tambahkan foreign key constraint |
$userTable | string|null | null | Nama tabel users (default: 'users') |
Contoh:
// Default: latest_editor_id dengan FK ke users table
$table->editor();
// Custom column name
$table->editor('updated_by');actor()
public function actor(
string $creatorColumn = 'creator_id',
string $editorColumn = 'latest_editor_id',
bool $withForeignKey = true,
?string $userTable = null
): voidMembuat kolom creator dan editor sekaligus.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$creatorColumn | string | 'creator_id' | Nama kolom creator |
$editorColumn | string | 'latest_editor_id' | Nama kolom editor |
$withForeignKey | bool | true | Tambahkan foreign key constraint |
$userTable | string|null | null | Nama tabel users (default: 'users') |
Contoh:
// Default: creator_id + latest_editor_id
$table->actor();
// Custom column names
$table->actor(
creatorColumn: 'created_by',
editorColumn: 'updated_by'
);
// Tanpa FK (microservice)
$table->actor(withForeignKey: false);dropCreator()
public function dropCreator(
string $column = 'creator_id',
bool $withForeignKey = true
): voidMenghapus kolom creator.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$column | string | 'creator_id' | Nama kolom |
$withForeignKey | bool | true | Hapus foreign key constraint |
Contoh:
BpmSchema::table('products', function ($table) {
$table->dropCreator();
});dropEditor()
public function dropEditor(
string $column = 'latest_editor_id',
bool $withForeignKey = true
): voidMenghapus kolom editor.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$column | string | 'latest_editor_id' | Nama kolom |
$withForeignKey | bool | true | Hapus foreign key constraint |
Contoh:
BpmSchema::table('products', function ($table) {
$table->dropEditor();
});dropActor()
public function dropActor(
string $creatorColumn = 'creator_id',
string $editorColumn = 'latest_editor_id',
bool $withForeignKey = true
): voidMenghapus kolom creator dan editor sekaligus.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$creatorColumn | string | 'creator_id' | Nama kolom creator |
$editorColumn | string | 'latest_editor_id' | Nama kolom editor |
$withForeignKey | bool | true | Hapus foreign key constraint |
Contoh:
BpmSchema::table('products', function ($table) {
$table->dropActor();
});Timestamp Methods
timestamps()
OVERRIDE
Overrides Laravel's default timestamps() method untuk include soft deletes by default.
public function timestamps(
bool $withoutSoftDelete = false,
bool $withBackdoor = false
): voidMembuat timestamp columns (created_at, updated_at, dan deleted_at).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$withoutSoftDelete | bool | false | Set true untuk skip deleted_at column |
$withBackdoor | bool | false | Set true untuk tambah backdoor_updated_at column |
Contoh:
// Default: created_at, updated_at, deleted_at
$table->timestamps();
// Tanpa soft deletes
$table->timestamps(withoutSoftDelete: true);
// Menghasilkan: created_at, updated_at
// Dengan backdoor timestamp
$table->timestamps(withBackdoor: true);
// Menghasilkan: created_at, updated_at, deleted_at, backdoor_updated_atCatatan: backdoor_updated_at menggunakan useCurrent() dan useCurrentOnUpdate(), berguna untuk tracking perubahan yang bypass Eloquent events.
Foreign Key Methods
NEW v0.4.0
BpmBlueprint menyediakan helper methods untuk foreign key dengan auto-detection tipe primary key dari Model dan support untuk Model classes.
Foreign key methods dibagi menjadi 2 kategori:
1. Primitive Methods (Chainable) - Column definition tanpa constraint, bisa dikustomisasi dengan chaining:
foreignFor()- Auto-detect type dari Model traitsforeignForId()- Force BIGINTforeignForUlid()- Force ULIDforeignForUuid()- Force UUID
2. Preset Methods (Opinionated) - Column + constraint langsung diterapkan, tidak bisa dichain:
foreignTable*()- 8 variants (auto/id/ulid/uuid — nullable/non-nullable)
Auto-Detection: Methods dengan auto-detect (foreignFor, foreignTable) mendeteksi tipe primary key dari Model traits:
HasUlidstrait → ULID columnHasUuidstrait → UUID column- No trait → BIGINT column
Parameter Support Matrix:
Tabel berikut menunjukkan parameter yang didukung oleh setiap foreign key method:
| Method | String Table | class-string<Model> | Model Instance | $column | Constraint | Auto-Discovery |
|---|---|---|---|---|---|---|
| foreignFor() | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ |
| foreignForId() | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| foreignForUlid() | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| foreignForUuid() | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| foreignTable() | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
| foreignTableNullable() | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
| foreignTableId() | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| foreignTableIdNullable() | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| foreignTableUlid() | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| foreignTableUlidNullable() | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| foreignTableUuid() | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| foreignTableUuidNullable() | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
Legend:
- ✅ Supported / Diterapkan
- ❌ Not Supported / Tidak diterapkan
- Auto-Discovery: Deteksi tipe PK dari Model traits (HasUlids/HasUuids)
- Constraint: Otomatis menerapkan
->constrained() - $column: Menerima parameter custom column name
Panduan Pemilihan Method:
DECISION TREE
Apakah kamu tahu tipe FK yang exact (BIGINT/ULID/UUID)?
✅ Ya, tipe sudah jelas
- Gunakan
foreignTable[Id|Ulid|Uuid]*() - Mendukung string table name, Model, dan custom column
- Contoh:
foreignTableUlid('products', 'main_product_id')
❌ Tidak, ingin auto-detect dari Model
- Gunakan
foreignFor*()atauforeignTable*() - Harus pass Model (class-string atau instance)
foreignFor*(): Tidak support custom column nameforeignTable*(): Support custom column name- Contoh:
foreignTable(Product::class, 'main_product_id')
foreignFor()
public function foreignFor(string|Model $related): ColumnDefinition|ForeignIdColumnDefinitionMembuat kolom foreign key dengan deteksi otomatis tipe primary key. Constraint TIDAK diterapkan, dapat dikustomisasi dengan chaining.
AUTO-DETECTION
Method ini auto-detect tipe primary key dari Model trait (HasUlids/HasUuids).
BREAKING CHANGE - v0.4.1
Parameter $column telah dihapus. Column name sekarang selalu auto-derived dari Model table name: singular(table_name)_id.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Model instance atau Model class (bukan string table name) |
Returns: ColumnDefinition\|ForeignIdColumnDefinition - Column definition untuk chaining
Throws: InvalidArgumentException - Jika parameter bukan Model class yang valid
Contoh:
use App\Models\{Product, User, Category};
// Product uses HasUlids → Creates ULID column 'product_id'
$table->foreignFor(Product::class)
->nullable()
->constrained()
->cascadeOnDelete();
// User uses HasUuids → Creates UUID column 'user_id'
$table->foreignFor(User::class)
->constrained();
// Category has no trait → Creates BIGINT column 'category_id'
$table->foreignFor(Category::class)
->constrained();
// ❌ BREAKING: Custom column name tidak lagi supported
// $table->foreignFor(Product::class, 'main_product_id'); // Error!
// ✅ Gunakan foreignTable*() jika butuh custom column name
$table->foreignTableUlid(Product::class, 'main_product_id');foreignForId()
public function foreignForId(string|Model $related): ColumnDefinitionMembuat kolom foreign key BIGINT tanpa constraint. Force BIGINT meskipun Model menggunakan ULID/UUID.
BREAKING CHANGE - v0.4.1
Parameter $column telah dihapus.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Model instance atau Model class |
Returns: ColumnDefinition - Column definition untuk chaining
Contoh:
// Force BIGINT 'product_id' even if Product uses HasUlids
$table->foreignForId(Product::class)
->constrained();foreignForUlid()
public function foreignForUlid(string|Model $related, int $length = 26): ColumnDefinitionMembuat kolom foreign key ULID tanpa constraint. Force ULID meskipun Model tidak menggunakan HasUlids.
BREAKING CHANGE - v0.4.1
Parameter $column telah dihapus.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Model instance atau Model class |
$length | int | 26 | Panjang kolom ULID |
Returns: ColumnDefinition - Column definition untuk chaining
Contoh:
// Force ULID 'product_id'
$table->foreignForUlid(Product::class)
->nullable()
->constrained();foreignForUuid()
public function foreignForUuid(string|Model $related): ColumnDefinitionMembuat kolom foreign key UUID tanpa constraint. Force UUID meskipun Model tidak menggunakan HasUuids.
BREAKING CHANGE - v0.4.1
Parameter $column telah dihapus.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Model instance atau Model class |
Returns: ColumnDefinition - Column definition untuk chaining
Contoh:
// Force UUID 'user_id'
$table->foreignForUuid(User::class)
->constrained();foreignTable()
public function foreignTable(
string|Model $related,
?string $column = null
): ForeignKeyDefinitionMembuat foreign key non-nullable dengan deteksi otomatis tipe + constraint. Opinionated method, constraint langsung diterapkan.
PRESET METHOD
Method ini langsung menerapkan constraint dan TIDAK bisa dichain dengan modifier. Gunakan foreignFor() jika butuh kustomisasi.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Model instance atau Model class |
$column | string|null | null | Nama kolom foreign key (default: auto-derived) |
Returns: ForeignKeyDefinition - Foreign key definition
Contoh:
use App\Models\Product;
// Auto-detect + constraint (column: product_id)
$table->foreignTable(Product::class);
// Custom column name
$table->foreignTable(Product::class, 'main_product_id');
// Equivalent to (without custom column):
// $table->foreignFor(Product::class)->constrained('products');foreignTableNullable()
public function foreignTableNullable(
string|Model $related,
?string $column = null
): ForeignKeyDefinitionMembuat foreign key nullable dengan deteksi otomatis tipe + constraint.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Model instance atau Model class |
$column | string|null | null | Nama kolom foreign key |
Returns: ForeignKeyDefinition - Foreign key definition
Contoh:
$table->foreignTableNullable(Product::class);
// Equivalent to:
// $table->foreignFor(Product::class)->nullable()->constrained('products');foreignTableId()
public function foreignTableId(
string|Model $related,
?string $column = null
): ForeignKeyDefinitionMembuat foreign key BIGINT non-nullable + constraint. Force BIGINT meskipun Model menggunakan ULID/UUID.
STRING TABLE SUPPORT
Method explicit type (foreignTableId/Ulid/Uuid) mendukung string table name selain Model.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Nama tabel (string), Model instance, atau Model class |
$column | string|null | null | Nama kolom foreign key |
Returns: ForeignKeyDefinition - Foreign key definition
Contoh:
// Force BIGINT dengan Model
$table->foreignTableId(Product::class);
// Force BIGINT dengan string table name
$table->foreignTableId('products');
// Custom column name
$table->foreignTableId('products', 'main_product_id');foreignTableIdNullable()
public function foreignTableIdNullable(
string|Model $related,
?string $column = null
): ForeignKeyDefinitionMembuat foreign key BIGINT nullable + constraint.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Nama tabel (string), Model instance, atau Model class |
$column | string|null | null | Nama kolom foreign key |
Returns: ForeignKeyDefinition - Foreign key definition
Contoh:
$table->foreignTableIdNullable('products');foreignTableUlid()
public function foreignTableUlid(
string|Model $related,
?string $column = null,
int $length = 26
): ForeignKeyDefinitionMembuat foreign key ULID non-nullable + constraint. Force ULID tanpa auto-detection.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Nama tabel (string), Model instance, atau Model class |
$column | string|null | null | Nama kolom foreign key |
$length | int | 26 | Panjang kolom ULID |
Returns: ForeignKeyDefinition - Foreign key definition
Contoh:
// Force ULID dengan Model
$table->foreignTableUlid(Product::class);
// Force ULID dengan string table name
$table->foreignTableUlid('products');
// Custom column name
$table->foreignTableUlid('products', 'main_product_id');foreignTableUlidNullable()
public function foreignTableUlidNullable(
string|Model $related,
?string $column = null,
int $length = 26
): ForeignKeyDefinitionMembuat foreign key ULID nullable + constraint.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Nama tabel (string), Model instance, atau Model class |
$column | string|null | null | Nama kolom foreign key |
$length | int | 26 | Panjang kolom ULID |
Returns: ForeignKeyDefinition - Foreign key definition
Contoh:
$table->foreignTableUlidNullable('products', 'optional_product_id');foreignTableUuid()
public function foreignTableUuid(
string|Model $related,
?string $column = null
): ForeignKeyDefinitionMembuat foreign key UUID non-nullable + constraint. Force UUID tanpa auto-detection.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Nama tabel (string), Model instance, atau Model class |
$column | string|null | null | Nama kolom foreign key |
Returns: ForeignKeyDefinition - Foreign key definition
Contoh:
$table->foreignTableUuid('users');foreignTableUuidNullable()
public function foreignTableUuidNullable(
string|Model $related,
?string $column = null
): ForeignKeyDefinitionMembuat foreign key UUID nullable + constraint.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | string|Model | - | Nama tabel (string), Model instance, atau Model class |
$column | string|null | null | Nama kolom foreign key |
Returns: ForeignKeyDefinition - Foreign key definition
Contoh:
$table->foreignTableUuidNullable('users', 'optional_user_id');Traits
HasCreator
MODEL TRAIT
Trait ini harus digunakan pada Eloquent Model untuk auto-tracking creator.
Trait untuk auto-fill creator_id saat model dibuat. Bekerja dengan kolom yang dibuat oleh $table->creator() di migration.
Namespace: Bpmlib\BpmMigration\Model\Trait\HasCreator
Contains:
Automatic Behavior
Trait ini otomatis register event listener saat model di-boot:
static::creating(function ($model) {
// Auto-set creator_id jika user authenticated
if (Auth::check() && !$model->isDirty('creator_id')) {
$model->creator_id = Auth::id();
}
});Behavior:
- Auto-fill
creator_iddenganAuth::id()saat model dibuat - Hanya jika user authenticated (
Auth::check()) - Skip jika
creator_idsudah diset manual (isDirty())
Customization (HasCreator)
Trait ini bisa dikustomisasi dengan override protected methods atau properties:
Custom column name:
class Product extends Model
{
use HasCreator;
protected $creatorColumn = 'created_by';
}Disable auto-fill:
class Product extends Model
{
use HasCreator;
protected $autoSetCreator = false;
}Disable relationship (microservice mode):
class Product extends Model
{
use HasCreator;
protected function hasCreatorRelation(): bool
{
return false;
}
}Public Methods (HasCreator)
creator()
public function creator(): BelongsToRelationship ke User model (limited columns).
Returns: BelongsTo - Relationship dengan select terbatas
Throws: RuntimeException - Jika relationship disabled
Contoh:
$product = Product::with('creator')->first();
echo $product->creator->name;creatorFull()
public function creatorFull(): BelongsToRelationship ke User model (all columns).
Returns: BelongsTo - Relationship tanpa select restriction
Contoh:
$product = Product::with('creatorFull')->first();
// Access all user columnsUtility Methods (HasCreator)
scopeCreatedBy()
public function scopeCreatedBy($query, $userId)Query scope untuk filter by creator.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$query | Builder | - | Query builder |
$userId | mixed | - | User ID |
Contoh:
$products = Product::createdBy(Auth::id())->get();setCreator()
public function setCreator($userId): selfManually set creator ID.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$userId | mixed | - | User ID |
Returns: self - Model instance untuk chaining
Contoh:
$product->setCreator($adminId)->save();getCreatorIdentity()
public function getCreatorIdentity(): arrayMendapatkan creator identity data dari model.
Returns: array - Array berisi creator info
Contoh:
$identity = $product->getCreatorIdentity();
// ['id' => 'ulid-creator-id']Denormalization (Advanced):
Untuk denormalized fields, override protected method fillCreatorDenormalized():
class Product extends Model
{
use HasCreator;
protected function fillCreatorDenormalized($user): void
{
$this->creator_name = $user->name;
$this->creator_email = $user->email;
}
}HasEditor
MODEL TRAIT
Trait ini harus digunakan pada Eloquent Model untuk auto-tracking editor.
Trait untuk auto-fill latest_editor_id saat model diupdate. Bekerja dengan kolom yang dibuat oleh $table->editor() di migration.
Namespace: Bpmlib\BpmMigration\Model\Trait\HasEditor
Contains:
Automatic Behavior (HasEditor)
Trait ini otomatis register event listener saat model di-boot:
static::updating(function ($model) {
// Auto-set latest_editor_id jika user authenticated
if (Auth::check() && !$model->isDirty('latest_editor_id')) {
$model->latest_editor_id = Auth::id();
}
});Behavior:
- Auto-fill
latest_editor_iddenganAuth::id()saat model diupdate - Hanya jika user authenticated (
Auth::check()) - Skip jika
latest_editor_idsudah diset manual (isDirty())
Customization (HasEditor)
Trait ini bisa dikustomisasi dengan override protected methods atau properties:
Custom column name:
class Product extends Model
{
use HasEditor;
protected $editorColumn = 'updated_by';
}Disable auto-fill:
class Product extends Model
{
use HasEditor;
protected $autoSetEditor = false;
}Disable relationship (microservice mode):
class Product extends Model
{
use HasEditor;
protected function hasEditorRelation(): bool
{
return false;
}
}Public Methods (HasEditor)
editor()
public function editor(): BelongsToRelationship ke User model (limited columns).
Returns: BelongsTo - Relationship dengan select terbatas
Contoh:
$product = Product::with('editor')->first();
echo $product->editor->name;editorFull()
public function editorFull(): BelongsToRelationship ke User model (all columns).
Returns: BelongsTo - Relationship tanpa select restriction
Utility Methods (HasEditor)
scopeEditedBy()
public function scopeEditedBy($query, $userId)Query scope untuk filter by editor.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$query | Builder | - | Query builder |
$userId | mixed | - | User ID |
Contoh:
$products = Product::editedBy($userId)->get();setEditor()
public function setEditor($userId): selfManually set editor ID.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$userId | mixed | - | User ID |
Returns: self - Model instance untuk chaining
Contoh:
$product->setEditor($adminId)->save();getEditorIdentity()
public function getEditorIdentity(): arrayMendapatkan editor identity data dari model.
Returns: array - Array berisi editor info
Denormalization (Advanced):
Untuk denormalized fields, override protected method fillEditorDenormalized():
class Product extends Model
{
use HasEditor;
protected function fillEditorDenormalized($user): void
{
$this->editor_name = $user->name;
}
}Global Macros
constrainedFor()
GLOBAL MACRO
Macro ini tersedia pada ColumnDefinition secara global setelah service provider di-boot.
Macro untuk shortcut ->constrained() dengan Model support. Alternative untuk .constrained() yang menerima Model class.
Registered On: Illuminate\Database\Schema\ColumnDefinition
Signature:
public function constrainedFor(Model|string $related): ColumnDefinitionParameters
| Name | Type | Default | Description |
|---|---|---|---|
$related | Model|string | - | Model instance atau Model class name |
Returns: ColumnDefinition - Column definition untuk chaining
Throws: InvalidArgumentException - Jika parameter bukan Model yang valid
Contoh:
use App\Models\Product;
// Tanpa macro (Laravel default)
$table->foreignUlid('product_id')->constrained('products');
// Dengan macro
$table->foreignUlid('product_id')->constrainedFor(Product::class);
// Dengan Model instance
$product = new Product();
$table->foreignUlid('product_id')->constrainedFor($product);Use Case:
Berguna saat menggunakan Laravel's native foreign key methods (foreignId, foreignUlid, foreignUuid) tanpa BpmBlueprint helpers:
// Standard Laravel (harus tahu nama tabel)
$table->foreignUlid('product_id')->constrained('products');
// Dengan constrainedFor (type-safe dengan Model)
$table->foreignUlid('product_id')->constrainedFor(Product::class);
// Kombinasi dengan chaining
$table->foreignUlid('product_id')
->constrainedFor(Product::class)
->cascadeOnDelete();Catatan: Jika menggunakan BpmBlueprint, lebih disarankan menggunakan foreignTable*() methods yang sudah include constraint:
// BpmBlueprint (recommended)
$table->foreignTableUlid(Product::class); // Sudah include constraint
// vs
// Laravel + macro
$table->foreignUlid('product_id')->constrainedFor(Product::class);Complete Usage Example
Contoh lengkap menggunakan semua classes dan traits:
<?php
// Migration
use Bpmlib\BpmMigration\BpmSchema;
use Illuminate\Database\Migrations\Migration;
return new class extends Migration
{
public function up(): void
{
BpmSchema::create('products', function ($table) {
$table->id();
$table->string('name');
$table->decimal('price', 10, 2);
// Foreign keys dengan auto-detection
$table->foreignTable(Category::class);
$table->foreignTableNullable(User::class, 'vendor_id');
// Actor tracking
$table->actor();
// Timestamps dengan soft deletes
$table->timestamps();
});
}
public function down(): void
{
BpmSchema::dropIfExists('products');
}
};
// Model
namespace App\Models;
use Bpmlib\BpmMigration\Model\Trait\{HasCreator, HasEditor};
use Illuminate\Database\Eloquent\{Model, SoftDeletes};
use Illuminate\Database\Eloquent\Concerns\HasUlids;
class Product extends Model
{
use HasUlids, SoftDeletes, HasCreator, HasEditor;
protected $fillable = ['name', 'price', 'category_id'];
// Relationships
public function category()
{
return $this->belongsTo(Category::class);
}
public function vendor()
{
return $this->belongsTo(User::class, 'vendor_id');
}
}
// Usage
$product = Product::create([
'name' => 'Sample Product',
'price' => 99.99,
'category_id' => $category->id,
]);
// creator_id auto-filled dari Auth::id()
echo $product->creator->name;
$product->update(['price' => 89.99]);
// latest_editor_id auto-filled dari Auth::id()
echo $product->editor->name;