--level used: 1The command larastan analyse throws an error on JsonResources that use $this->pivot. I've an User model with a m:m relationship to another table. UserResource will load some data of the pivot table if it is requested using the method whenPivotLoaded. The problem is that Larastan does not recognize the pivot as a valid property.
The error that Larastan throws is this:
{
"description": "Access to an undefined property App\\Http\\Resources\\UserResource::$pivot.",
"fingerprint": "b910d56075e641d4c94e7412d3e499d7b832002568a667e1d5ee2ca0c888e18b",
"location": {
"path": "app/Http/Resources/UserResource.php",
"lines": {
"begin": 45
}
}
},
/**
* @extends JsonResource<\App\User>
*/
class UserResource extends JsonResource
{
// Other parts of the resource omitted
public function toArray($request)
{
return [
"time_to_live" => $this->whenPivotLoaded("table", function () {
return $this->pivot->time_to_live; // This is the line 45
})
];
}
}
Thank you for reporting!
I guess we can add a special case for pivot with return type mixed
Yea I was digging into the source code in hope to help find a solution and that seems the right way to do it, just "white list" it
Hm, I don't necessarily think this is specific to resources. @ludo237 does this problem exist outside of resources in your codebase?
The only error that larastan triggers is on $pivot property on JsonResources. I've used the reccomended PHPDoc for larastan 0.5+
One of the possible solutions is we can tell in ModelPropertiesExtension that pivot exists in Model. And also add \Illuminate\Database\Eloquent\Relations\Pivot to the universalObjectCrates Because we can't tell which properties exist on the pivot table.
I see, we'll also have to account for the customized pivot attribute name, as it can't be assumed to be pivot
@mr-feek a configuration should do the trick
UPDATE
Apparently you can easily fix this without any change to this package. Basically if you call getRelationValue("pivot") instead of relying to the magic property Larastan gets happy about it 馃ぃ
@mr-feek @canvural
/**
* @extends JsonResource<\App\User>
*/
class UserResource extends JsonResource
{
// Other parts of the resource omitted
public function toArray($request)
{
/** @var \App\User **/
$user = $this;
return [
"time_to_live" => $this->whenPivotLoaded("table", function () use($user) {
return $user->getRelationValue("pivot")->time_to_live; // This is the line 45
})
];
}
}
Most helpful comment
UPDATE
Apparently you can easily fix this without any change to this package. Basically if you call
getRelationValue("pivot")instead of relying to the magic property Larastan gets happy about it 馃ぃ@mr-feek @canvural