Using Lazy::whenLoaded with Larastan #279
-
Looking for some advice on using Lazy::whenLoaded with Larastan. Suppose I have a setup where blogposts belong to users and my BlogPostData class looks like this: class BlogPostData extends Data
{
public function __construct(
public string $id,
...
public Lazy|UserData $user,
){}
public static function fromModel(BlogPost $bp): BlogPostData
{
return new self(
id: $bp->id,
..
user: Lazy::whenLoaded('user', $bp, fn() => UserData::fromModel($bp->user)),
);
}
} Larastan gives the following error because $user is a non nullable parameter in my UserData::fromModel method.
I could update UserData::fromModel() to accept a nullable param but then I'd have to throw an exception if it's not set. public static function fromModel(?User $user): UserData
{
if (!$user) {
throw new Exception();
}
return new self(
id: $user->id, This works ok, but seems messy. Just wondering if there's a better way that I'm overlooking. Edit: public static function fromModel(BlogPost $bp): BlogPostData
{
return new self(
id: $bp->id,
user: Lazy::whenLoaded('user', $bp, function () use ($bp) {
/** @var User $user */
$user = $bp->user;
return UserData::fromModel($user);
}), |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I think you should use this way it should handle with fn() => UserData::from($bp->user) |
Beta Was this translation helpful? Give feedback.
Hi @benbjurstrom
I think you should use
from
as a function to create an object because it is a magical-creation and notfromModel
this way it should handle with
null
value.