Why override toArray() instead of using accessor

Posted 3 years ago by canfiax

I curiously peeked around the code, and saw that Taylor did the following:

 * Convert the model instance to an array.
 * @return array
public function toArray()
    $array = parent::toArray();

    $array['tax_rate'] = $this->taxPercentage();

    return $array;

But I wonder why he would override the toArray() method like he did above, and not just define an accessor like this:

public function getTaxRateAttribute() {
    return $this->attributes['tax_rate'] = $this->taxPercentage();

Then, when you call ->toArray(), tax_rate would be included.

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