skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 :

    protected $with = ['roles'];
    

    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 (:'


  2. It depends on a relationship that might not be loaded? Try adding this to your accessor.

    public function getCurrentRoleAttribute()
    {
        $this->loadMissing('roles');
    
        return $this->roles->first();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search