Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message
Constrained Morph To For Laravel

Constrained Morph To For Laravel Laravel Package

pindab0ter/constrained-morph-to-for-laravel

Type-constrained polymorphic relationships for Laravel Eloquent. Extend morphTo to accept only specified model types, ensuring type safety and data integrity while keeping the flexibility of a polymorphic database structure.

View on GitHub
Deep Wiki
Context7

Constrained MorphTo for Laravel brings type-safe polymorphic relationships to Eloquent. Instead of a morphTo resolving to any model, you declare exactly which model classes a relation may return—keeping polymorphic database flexibility while enforcing data integrity.

return $this->constrainedMorphTo([Post::class, Video::class], 'commentable_type', 'commentable_id');
  • Restrict relations to one or more allowed model types
  • Simple HasConstrainedMorphTo trait with a familiar API
  • Prevents invalid polymorphic data at query time
  • Works alongside standard Eloquent relationships
Frequently asked questions about Constrained Morph To For Laravel
How do I restrict a polymorphic relationship to only accept specific model types in Laravel?
Use the `constrainedMorphTo` method from this package, passing an array of allowed classes (e.g., `[Post::class, Video::class]`). This replaces the standard `morphTo` and enforces type constraints at runtime, returning `null` for invalid types.
Does this package work with Laravel 11 or 12? What about older versions?
The package officially supports Laravel 10.48+, 11.x, and 12.x. Laravel 13 is supported in version 1.2.0+. Older versions may work but aren’t guaranteed due to breaking changes in Eloquent’s polymorphic handling.
Will existing `morphTo` relationships break if I switch to `constrainedMorphTo`?
No, existing `morphTo` relationships remain unchanged. The package only adds constraints when explicitly used. However, unconstrained relationships will still accept any model type, so you’ll need to migrate them intentionally.
Can I use custom column names (not `model_type`/`model_id`) for constrained polymorphic relationships?
Yes, you can specify custom column names as the second and third arguments to `constrainedMorphTo` (e.g., `constrainedMorphTo([Post::class], 'custom_type', 'custom_id')`). This is useful for legacy schemas or non-standard polymorphic setups.
How does this package handle invalid model types during runtime? Does it throw exceptions?
The package returns `null` for invalid model types instead of throwing exceptions. You’ll need to handle this in your business logic, such as logging the issue or providing fallback behavior (e.g., redirecting to a default model).
Is there a performance impact when using constrained polymorphic relationships in high-traffic APIs?
The performance impact is minimal for most use cases, as constraints are enforced via `instanceof` or class comparison during query resolution. However, for critical API endpoints with frequent polymorphic filters, benchmarking is recommended to ensure no bottlenecks.
Does this package support Laravel’s `morphMap` for custom model name mappings?
Yes, the package aligns with Laravel’s `morphMap` and supports custom model name mappings. For example, if you’ve mapped `Post::class` to `'posts'`, the constraints will respect this mapping during type validation.
How do I test constrained polymorphic relationships in PHPUnit?
Test by asserting the returned model type matches the allowed constraints. For example, use `assertInstanceOf(Post::class, $comment->commentable())` for single-type constraints or `assertInstanceOf(Post::class | Video::class, $comment->commentable())` for multi-type constraints. Mock invalid types to verify `null` is returned.
Are there any known conflicts with other Laravel packages like `spatie/laravel-activitylog` or `laravel-nova`?
Potential conflicts may arise if third-party packages modify polymorphic behavior globally (e.g., via scopes or macros). Test thoroughly in your environment, especially if using packages that alter `morphTo` logic or add custom query constraints.
What’s the best way to handle legacy polymorphic data that might contain invalid types after enabling constraints?
Run data migrations or validation layers to clean up invalid records before enforcing constraints. Alternatively, use a hybrid approach where constraints are optional for specific relationships until legacy data is resolved. Log invalid types for manual review if needed.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route