Vehicle → Car, Truck).Blueprint macros and Eloquent’s existing STI capabilities, reducing friction with native tooling (e.g., migrations, queries).sti() macro simplifies schema changes, but requires manual validation of existing type columns (e.g., legacy databases).belongsTo).WHERE type = ? clauses. Indexing the type column mitigates this.type values or missing subclasses can cause runtime errors (e.g., ClassNotFoundException). Validation logic must be added.type column without downtime?type lookups)?composer.json constraints). Test against the target Laravel version.type column constraints (e.g., ENUM) may need adjustment.type column to the target table using the sti() macro:
Schema::table('vehicles', function (Blueprint $table) {
$table->sti()->nullable(); // or ->default('vehicle')
});
type values:
DB::table('vehicles')->update(['type' => 'car']); // Example
class Vehicle extends Model {
use SingleTableInheritance;
}
class Car extends Vehicle {}
class Truck extends Vehicle {}
config/app.php (handled automatically via composer require).booted() method to the root model to validate type values:
protected static function booted() {
static::addGlobalScope('ValidType', function (Builder $builder) {
$builder->whereIn('type', ['car', 'truck']);
});
}
Vehicle::all() will return mixed Car/Truck instances. Update type hints and casts accordingly.Vehicle::morphMany()) may need adjustments to handle subclasses.model_keys or custom serialization.vehicles_sti) to test patterns.Car::validate()) works as expected.ClassNotFoundException or query timeouts.type column with an ENUM or constrained set to prevent invalid values.type values) to avoid orphaned data.type column and model inheritance chain.class Vehicle extends Model {
protected static function booted() {
static::creating(function ($model) {
logger()->debug("Creating {$model->type} (class: " . get_class($model) . ")");
});
}
}
type values, circular dependencies).hasOne/belongsTo without workarounds).type column:
Schema::table('vehicles', function (Blueprint $table) {
$table->string('type')->index();
});
SELECT * on large STI tables; explicitly load only needed attributes.type (if supported by the DB) can help with scaling.| Failure Scenario | Impact | Mitigation |
|---|---|---|
Invalid type value in DB |
Runtime ClassNotFoundException |
Add global scope to filter invalid types. |
| Missing subclass definition | Silent failures or errors | Use a fallback root model or throw exceptions. |
Unindexed type column |
Slow queries | Add index during migration. |
| Circular subclass dependencies | Infinite loops in logic | Enforce linear inheritance in code reviews. |
| Cache corruption (serialized models) | Inconsistent data retrieval | Avoid caching mixed model types; use model_keys. |
MODELS.md file with subclass relationships.How can I help you explore Laravel packages today?