You should not (cannot) rely on instance state inside relationship methods
Eloquent: with() not working for relation depending on a model attribute
Hello!
In my app, I have a User model and a License model. A user can have multiple licenses. Also, a user can be a parent or a subuser. This is denoted by the parent_id field in the users table, which is NULL if the user is a parent. Only the parent user has licenses.
In the User model, I have a method for retrieving the latest license:
public function license(): HasOne
{
return !is_null($this->parent_id) ? $this->parent->license() : $this->hasOne(License::class)->latestOfMany();
}
If the user is a subuser, it returns the parent's license. Otherwise, it returns a HasOne relationship.
This works fine when doing something like this:
$subuser = User::find($subuserId);
dd($subuser->license);
However, if I try to use with(), for example:
$subuser = User::with('license')->find($subuserId);
dd($subuser->license);
this will fail, because inside the license() method, the model's attributes are not loaded at the time with() runs (i.e. $this->attributes is null).
How can I make this work?
you should get the collection with the child licence (if there is one) and parent licence, and then create an accessor on the model so that when you get model->licence, the accessor can do the evaluation against the model instance
You will need to choose a different name for the accessor so that it does not conflict with the license relation.
Please or to participate in this conversation.