Auto-discover nested policies following conventional, parallel hierarchy #54493
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
A few times now I have read the docs and interpreted that if my models are under
app/Modelsand my policies underapp/Policies, my policies will be auto-discovered. This is true, except for my nested models and policies.Currently, Laravel will not auto-discover the policy
app/Policies/Nested/PostPolicyfor the modelapp/Models/Nested/Post. This has to be registered explicitlyThis PR resolves smooths out this exception of policy auto-discovery and removes the need for explicit registration for this conventional app structure.
While I don't see this to be a breaking change, I am targeting Laravel 12 as this discovers new paths and allows developers to remove explicit registration for models/policies using this conventional, parallel class hierarchy (optional).
Implementation Details
When the model class contains a
Modelssub-namespace two additional paths are added to auto-discovery: a sibling path ofPoliciesand a subpath ofModels/Policies.This aligns with the algorithm outlined in the documentation, but anchors it to the model path. Since this is simply a string replacement, this should support both conventional structures as well as "modular" structures.
Examples:
App\Models\Auth\Userauto-discoversApp\Policies\Auth\UserPolicyorApp\Models\Policies\Auth\UserPolicySome\Domain\Models\Auth\Userauto-discoversSome\Domain\Policies\Auth\UserPolicyorSome\Domain\Models\Policies\Auth\UserPolicy