I'm using the latest version of PhpStorm (2022.3.1) and Laravel 9 . This is not a huge issue, but rather a major eyesore.
For some reason when I use a Model to create a custom Attribute like this:
public function getFormattedStartDateAttribute(): string
{
if (!$this->start_date) {
return 'TBD';
} else {
return $this->start_date->format('M. d, Y');
}
}
And use in the view like this or this:
- Date
{{ $event->formattedStartDate }}
- Date
{{ $event->formatted_start_date }}
PhpStorm still says the method has no usages
?
Is there a way to fix this? I've tried reindexing my project. This is a new feature called Code Vision.
CodePudding user response:
The issue is very easy to solve, you can use barryvdh/laravel-ide-helper
and then run php artisan ide:model
, that will go over the models and create a PHPDoc block (you can add options and create them in the same model file or in a new file where you only have this PHPDock blocks), and PHPStorm will read this doc block and know when you are calling attributeWhatever
is what type.
It will add this in your case:
/**
* @property string $formattedStartDate
*/
This way, any IDE that is capable of understanding PHPDock blocks, will understand that when you do $class->formattedStartDate
, you are refering to that one, and it is of type string
.
BUT, no IDE (unless using a plugin that I am not aware of) will understand that getFormattedStartDateAttribute
-> formattedStartDate
, so you will still get no usages
for getFormattedStartDateAttribute
, but at least you can track formattedStartDate
and do whatever you want with it.
One quick tip, if you are using Laravel 9 , please change that code from:
public function getFormattedStartDateAttribute(): string
{
if (!$this->start_date) {
return 'TBD';
} else {
return $this->start_date->format('M. d, Y');
}
}
To:
public function formattedStartDate(): \Illuminate\Database\Eloquent\Casts\Attribute
{
return Attribute::get(
function ($value, $attributes) {
if (! $attributes['start_date']) {
return 'TBD';
} else {
return $attributes['start_date']->format('M. d, Y');
}
}
);
}
Why? Because using getFormattedStartDateAttribute
is the old way, Laravel 9 made it easier, read about Accessors.
See that getXXXXAttribute
and setXXXXAttribute
is not even present on the documentation anymore.