I have an appended attribute that works when I do Model::first()->appended_attribute
, but when get the model object instantiated through laravel’s route dependency injection like below :
public function update(UserRequest $request, User $user)
{
$user->appended_attribute; // returns null
}
When I access it it returns null
, Though when I do $user->toArray()
the appended attributes does exist but with a value of null.
And if I do this :
public function update(UserRequest $request, User $user)
{
User::find($user->id)->appended_attribute; // returns it's correct value
}
It does work.
The append attribute method :
public function getCurrentRoleAttribute()
{
return $this->roles->first();
}
Is there anything I’m missing ?
2
Answers
Short answer:
It's a miss use of spatie's permissions package.
Long answer:
Thanks to @IGP 's answer for giving me a hint about the missing relation load, I found out that it's not that it's missing, it's actually the opposite !!. After removing this line from the user model it worked :
It was because I'm using spatie's permissions package which uses the team_id provided after the user's login to load the user's
roles
relation (in that team). Now me setting the relation to be eagerly loaded with the$with
property is basically saying load the relation before setting the team_id !!, That's why it was returning null.SORRY FOR NOT PROVIDING MORE INFO ABOUT THE ISSUE (:'
It depends on a relationship that might not be loaded? Try adding this to your accessor.