pindab0ter/constrained-morph-to-for-laravel
Strengths:
morphTo while adding constraints via a decorator pattern (likely via traits or macros).ModelNotFoundException for invalid morph maps).Weaknesses:
Laravel Compatibility:
morphs table with model_type/model_id).morphTo logic or third-party packages altering polymorphic behavior (e.g., spatie/laravel-activitylog).Implementation Complexity:
use ConstrainedMorphTo;).class Post extends Model {
use ConstrainedMorphTo;
public function constrainedMorphTo(): array {
return [User::class, Comment::class]; // Only allow these types
}
}
Runtime Overhead:
instanceof or get_class()).Edge Cases:
morphTo records with invalid types will fail silently unless explicitly handled.Testing Requirements:
null values, custom model namespaces).morphMap or globalScope.Use Case Validation:
Adoption Risks:
Alternatives:
tap() in relationship definitions)?Migration Strategy:
null, exception, or silent ignore)?Primary Fit:
morphTo, morphMany).Post, User, Media).Secondary Fit:
Non-Fit:
morph-to with custom logic).Assessment Phase:
Post::morphTo() should only resolve to User or Admin).model_type values not in morphMap).Pilot Implementation:
ActivityLog) and add constraints:
class ActivityLog extends Model {
use ConstrainedMorphTo;
public function constrainedMorphTo(): array {
return [User::class, Service::class];
}
}
InvalidMorphTypeException).null, non-existent classes).Gradual Rollout:
Dependency Updates:
morphMap or custom resolveMorphClass() logic.spatie/laravel-activitylog).Laravel Versions:
Database:
model_type if querying by constrained types frequently.Testing:
| Step | Task | Dependencies | Risk |
|---|---|---|---|
| 1 | Audit polymorphic relationships | None | Low |
| 2 | Pilot with low-risk model | Audit results | Medium |
| 3 | Write validation tests | Pilot implementation | High |
| 4 | Gradual rollout to other models | Pilot success | Medium |
| 5 | Data cleanup (if needed) | Rollout progress | High |
| 6 | Document constraints | All constraints defined | Low |
Pros:
ModelNotFoundException).Cons:
Developer Experience:
InvalidMorphTypeException).Onboarding:
Error Handling:
400 Bad Request for invalid types).Performance:
instanceof or cached class comparisons).static property).Database:
How can I help you explore Laravel packages today?