Property type isn't detected when casting Eloquent attributes to spatie/laravel-data
Data objects
#1400
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.
The problem
When casting Eloquent attributes to
spatie/laravel-data
Data objects, ide-helper doesn't pick the correct class. For example, the example from Spatie's documentation https://spatie.be/docs/laravel-data/v2/advanced-usage/eloquent-casting:Running
php artisan ide-helper:models --dir='app' --write
generates this DocBlock:This means that we don't get the benefit of type-hinting for casted attributes like this:
Why does this happen?
This happens because
src/Support/EloquentCasts/DataEloquentCast.php
from Spatie's package specifies a return type. This is what ide-helper picks up:Proposed change
I put this together when looking through the code, trying to work out how to fix it in a project of mine. I thought I'd turn it into a PR for discussion…
This PR lets you instruct ide-helper to use the class that was specified, by adding the DocBlock tag
@ide-helper-eloquent-cast-to-specified-class
to the class being cast to. e.g.From which, ide-helper now generates:
Notes
@ide-helper-eloquent-cast-to-specified-class
tag can be added to a class, or any of it's parents.spatie/laravel-data
could add this tag to theirSpatie\LaravelData\Data
class, so it's always applied to Data classes that use it. But if they don't, it can just as easily be added to Data classes (or a parent class) in individual projects.spatie/laravel-data
. It can be used for any classes being cast to in this manner.Thoughts
Other issues and PRs
spatie/laravel-data
does specify a return type. So whilst it might be a useful change, it doesn't affect this situation.spatie/laravel-data
. This seems inflexible to me as it wouldn't allow for other packages or custom classes to benefit.Type of change
Checklist
composer fix-style