t0berius
6 months ago

laravel accessor appends not working as expected / strange behavior

Posted 6 months ago by t0berius

I'm using an accessor on my user model:

User:

protected $appends = ['is_vendor'];

public function vendorDetails()
{
    return $this->hasOne('App\VendorUser');
}

//returns the vendor status of a user
public function getIsVendorAttribute()
{
    return (is_null($this->vendorDetails)) ? false : true;
}

public function currentLevel(){

    if($this->is_vendor)
        return $this->hasOne('App\VendorLevel', 'id', 'current_level');
    else
        return $this->hasOne('App\UserLevel', 'id', 'current_level');
}

Using

$vendor->currentLevel

inside my controller returns a UserLevel for the current user, but when I call

    dd($product->vendor->is_vendor);

it's returning true. Any idea where things go wrong? When I dump the whole user object:

dd($vendor);

I can see the append attribute only in the appendssection:

#appends: array:1 [▼
  0 => "is_vendor"
]

It's not listed under the #attributes property of the model.

Please sign in or create an account to participate in this conversation.